Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove duplicates (both values) - duplicate values from an ArrayList

Tags:

java

arraylist

I have an ArrayList with the following strings;

 List<String> e = new ArrayList<String>();
 e.add("123");
 e.add("122");
 e.add("125");
 e.add("123");

I want to check the list for duplicates and remove them from the list. In this case my list will only have two values, and in this example it would be the values 122 and 125, and the two 123s will go away.

What will be the best way to this? I was thinking of using a Set, but that will only remove one of the duplicates.

like image 298
danilo Avatar asked Oct 14 '15 13:10

danilo


People also ask

How do I remove all duplicates from a list?

To remove the duplicates from a list, you can make use of the built-in function set(). The specialty of the set() method is that it returns distinct elements.


2 Answers

In Java 8 you can do:

e.removeIf(s -> Collections.frequency(e, s) > 1);

If !Java 8 you can create a HashMap<String, Integer>. If the String already appears in the map, increment its key by one, otherwise, add it to the map.

For example:

put("123", 1);

Now let's assume that you have "123" again, you should get the count of the key and add one to it:

put("123", get("aaa") + 1);

Now you can easily iterate on the map and create a new array list with keys that their values are < 2.

References:

  • ArrayList#removeIf
  • Collections#frequency
  • HashMap
like image 182
Maroun Avatar answered Sep 26 '22 10:09

Maroun


You can also use filter in Java 8

e.stream().filter(s -> Collections.frequency(e, s) == 1).collect(Collectors.toList())
like image 26
Sajan Chandran Avatar answered Sep 23 '22 10:09

Sajan Chandran