How to remove duplicates from a list of objects based on "String" property in Java 8? I can find code for Int or long property only but unable to find string comparison when string are difference case and get unique list.
Following is program i am trying to achieve.
public class Diggu {
class Employee{
private int id;
private String name;
public Employee(int id, String name){
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public void ra(){
List<Employee> employee = Arrays.asList(new Employee(1, "John"), new Employee(3, "JOHN"), new Employee(2, "BOB"));
System.out.println(""+ employee.size());
List<Employee> unique = employee.stream()
.collect(collectingAndThen(toCollection(() -> new TreeSet<>(comparing(Employee::getName))),
ArrayList::new));
System.out.println(""+ unique.size());
}
public static void main(String[] args) {
new Diggu().ra();
}
}
Result:
run:
3
3
BUILD SUCCESSFUL (total time: 2 seconds)
Where it should be 3 and 2