Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

Assuming I have some collection, how could I quickly 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 more elegant .stream()-solution I’m missing.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading