1

Hi I want to use lambda in java to remove duplicate elements in a list . Define if it is duplicate will be by a custom function Let's suppose we have these objects:

Object1(id:1 , name:"SEVERO" , grade:"A")
Object2(id:2 , name:"SEVERO" , grade:"B")
Object3(id:3 , name:"LUCY" , grade:"A")
Object4(id:4 , name:"LUCY" , grade:"A")
Object5(id:5 , name:"PAULA" , grade:"A")


Expected results:

Object2(id:2 , name:"SEVERO" , grade:"B")
Object3(id:3 , name:"LUCY" , grade:"A")
Object5(id:5 , name:"PAULA" , grade:"A")

So basically if there are objects with same name, I only want to keep one of them. The one that will be kept is the one with the highest grade (order of grades: A->B->C), in case there is a tie based on the grade, any of the objects can be kept , there is not preference.

How can I do this using java lambda?

Deibys
  • 619
  • 3
  • 9
  • 18
  • 1
    "The one that will be kept is the one with the highest grade" then probably you want to keep `Object1(id:1 , name:"SEVERO" , grade:"A")`, instead of `Object2(id:2 , name:"SEVERO" , grade:"B")`. – Pshemo Nov 28 '19 at 21:48
  • Also do you want to modify list or just get some data *from* it? – Pshemo Nov 28 '19 at 21:50

2 Answers2

5

I'd go with the toMap collector:

Collection<Student> result = source.stream()
                .collect(toMap(Student::getName, Function.identity(),
                        BinaryOperator.minBy(Comparator.comparing(Student::getGrade))))
                .values();
  • source is the collection we're streaming upon.
  • Student is the objects in the source (of course this is just an assumption which you should change to the name of the objects in your collection).
  • Student::getName is the keyMapper used to extract the keys for the map.
  • Function.identity() is the valueMapper used to extract the values for the map.
  • BinaryOperator.minBy(Comparator.comparing(Student::getGrade)) is the merge function used to resolve conflicts in the case two given objects have the same name.
  • values yields the values of the map as we no longer care about the keys.

if you want exactly a List<T> instead of a Collection<T> then feel free to pass the result of the above pipeline into the ArrayList<>(...) constructor.

Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

You can also take a look at this question, which is more generic and has a lot of good answers:

Java 8 Distinct by property

Edwin
  • 33
  • 6