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);
}
}
Have a
maintain count and number, at the end iterate keyset and get values with more than one count
You could hire a magic elf and let it do it for you. How would you ever want to do this without looping through it? If you don't loop through the list, you even won't be able to have a look at the elements. It is like you want to sum a whole bunch of numbers together without looking at those numbers. Summing elements is much easier than searching for duplicates or searching for unique elements. In general, 97% of what code does is looping through lists and data and process and update it.
So, said that, you have to loop. Now you might want to choose the most efficient way. Some methods come to mind:
contains
loops through the list of course.))Your
List
should ideally have been aSet
which doesn't allow duplicates in the first place. As an alternative to looping, you could either convert and switch toSet
or use it intermediately to eliminate duplicates as follows:Here's my version of the solution:
It adds numbers from 0 to 9 to a list, and it adds to another list what is in "duplicate" (a number followed by the same number). You can use your big list instead of my randomNumbers ArrayList.