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 case).
Is there any other efficient way rather than looping through list ? I asked this question because the list that I am working is very large ? My code is
List<Long> duplicate = new ArrayList();
for (int i = 0; i < list.size(); i++) {
Long item = (Long) list.get(i);
if (!duplicate.contains(item)) {
duplicate.add(item);
}
}
With Guava and Java 8, it's trivial and fast:
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:
I like answer Java 8, Streams to find the duplicate elements. Solution return only unique duplicates.
Given that you can do this by looping through the list only once, I wouldn't worry about performance too much. If you search for more performant solutions then you'll probably end up over-complicating the code and the readability and maintainability will suffer. At the end of the day, if you want to check the whole list for duplicates then you have to visit every element.
I'd advise writing the obvious solution and see how it performs. You'll probably be surprised how fast Java can iterate over a list, even if it is particularly large.
Some good answers so far but another option just for the fun of it. Loop through the list trying to place each number into a Set e.g. a HashSet. If the add method returns false you know the number is a duplicate and should go into the duplicate list.
EDIT: Something like this should do it
I am not sure about the efficiency, but I find the code easy to read (and that should be preferred.
EDIT: changing
Lists.newArrayList()
tonew ArrayList<Number>();