Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java stream - find unique elements

I have List<Person> persons = new ArrayList<>(); and I want to list all unique names. I mean If there are "John", "Max", "John", "Greg" then I want to list only "Max" and "Greg". Is there some way to do it with Java stream?

like image 724
Greg_M Avatar asked Sep 11 '25 02:09

Greg_M


2 Answers

We can use streams and Collectors.groupingBy in order to count how many occurrences we have of each name - then filter any name that appears more than 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]
like image 55
Nir Alfasi Avatar answered Sep 13 '25 15:09

Nir Alfasi


List persons = new ArrayList();
    persons.add("Max");
    persons.add("John");
    persons.add("John");
    persons.add("Greg");

    persons.stream()
             .filter(person -> Collections.frequency(persons, person) == 1)
             .collect(Collectors.toList());
like image 22
Rajesh Mbm Avatar answered Sep 13 '25 14:09

Rajesh Mbm