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
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)));