Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select duplicate values from a list in java?

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);
         }
     }
like image 234
Script_Junkie Avatar asked Jun 25 '13 22:06

Script_Junkie


2 Answers

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:

  • Sort all the numbers and then loop only once through it to find duplicates (since they will be next to each other). However, keep in mind that sorting algorithms also loop through the data.
  • For each element in the list, check if there is another element with the same value. (This is how you did it. This means you have two loops inside each other. (contains loops through the list of course.))
like image 190
Martijn Courteaux Avatar answered Oct 14 '22 18:10

Martijn Courteaux


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

like image 40
Jiri Kremser Avatar answered Oct 14 '22 16:10

Jiri Kremser