Java stream - find unique elements -
i have list<person> persons = new arraylist<>();
, want list unique names. mean if there "john", "max", "john", "greg" want list "max" , "greg". there way java stream?
we can use streams , collectors.groupingby
in order count how many occurrences have of each name - filter name appears more once:
list<string> res = persons.stream() .collect(collectors.groupingby(function.identity(), collectors.counting())) .entryset() .stream() .filter(e -> e.getvalue() == 1) .map(e -> e.getkey()) .collect(collectors.tolist()); system.out.println(res); // [max, greg]
Comments
Post a Comment