Search code examples
java

Return only the unique values from collection, removing all occurrences of duplicates


Assuming I have some collection, how could I return only those values that appear exactly once? I don't want to reduce duplicate values down to a single entry, I want to eliminate them completely - these are non-valid for my use case.

As an example, a list containing 1, 2, 3, 1, 4, 3, 5, 1 should only return 2, 4, 5. I could loop over the list, count the elements and then remove all that appear more than once, but I'm wondering if there's a .stream() solution I'm missing.


Solution

  • To return only elements that appear exactly once, you can use Stream to achieve that:

    List<Integer> list = Arrays.asList(1, 2, 3, 1, 4, 3, 5, 1);
    
    //Find Number of occurence of each element in the List 
    
    Map<Integer, Long> counts = list.stream()
        .collect(Collectors.groupingBy(e -> e, Collectors.counting()));
    
    // Filter elements that appear only once
    
    List<Integer> result = list.stream()
        .filter(element -> counts.get(element) == 1)
        .toList();