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);
}
}
Is there any other efficient way rather than looping through list ?
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.))List<Number> inputList = Arrays.asList(4, 6, 6, 7, 7, 8);
List<Number> result = new ArrayList<Number>();
for(Number num : inputList) {
if(Collections.frequency(inputList, num) > 1) {
result.add(num);
}
}
I am not sure about the efficiency, but I find the code easy to read (and that should be preferred.
EDIT: changing Lists.newArrayList()
to new ArrayList<Number>();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With