S
S
Sland Show2018-10-03 14:29:47
Java
Sland Show, 2018-10-03 14:29:47

How to remove all unique elements from a collection?

How can I gracefully remove all unique data from a list?
For example, from this:

List<String> list = new ArrayList<>();
 list.add("A");
 list.add("B");
 list.add("C");
 list.add("A");
 list.add("B");
 list.add("X");

That is, all unique values ​​\u200b\u200bmust be deleted - C and X in this case.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Сергей Горностаев, 2018-10-03
@SlandShow

list = list.stream()
            .collect(Collectors.groupingBy(
                Function.identity(),
                Collectors.counting()))
            .entrySet()
            .stream()
            .filter(e -> e.getValue() > 1)
            .map(Map.Entry::getKey)
            .collect(Collectors.toList());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question