How to select duplicate values from a list in java?

后端 未结 13 834
傲寒
傲寒 2021-01-18 00:38

For example my list contains {4, 6, 6, 7, 7, 8} and I want final result = {6, 6, 7, 7}

One way is to loop through the list and eliminate unique values (4, 8 in this

13条回答
  •  无人及你
    2021-01-18 01:32

    With Guava and Java 8, it's trivial and fast:

    Multiset multiset = HashMultiset.create(list);
    return list.stream()
        .filter(i -> multiset.count(i) > 1)
        .collect(Collectors.toList());
    

    The first line computes the counts using a sort of a hash map. The remainder is more than obvious.

    Something like this could simulate the multiset:

    HashMap multiset = new HashMap<>();
    list.stream().forEach(i -> 
        multiset.compute(i, (ignored, old) -> old==null ? 1 : old+1)));
    

提交回复
热议问题