Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find duplicate value in array list and print the duplicated value

Tags:

java

arraylist

I have an Arraylist of names, I want to see duplicated values if exist and print this value. The problem is that I'm getting confused on whether to use contains method or not, the below code is not working.

ArrayList<String> list=new ArrayList();
        list.add("Sagio Mane");
        list.add("Karius");
        list.add("Mo Salah");
        list.add("Firmino");
        list.add("Lovren");
        list.add("Steven Gerrard");
        list.add("Karius");
        list.add("Mo Salah");

    for(int i =0; i < list.size(); i++) {
         if list.contains(list.get(i)) {
             System.out.println(list.get(i)+" is duplicated")
         }
    }

This should print "karius is duplicated"

like image 357
Valek Avatar asked May 27 '18 07:05

Valek


People also ask

How do you find duplicate values in an array?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }


1 Answers

If you are using Java 8+ you can use :

//Get frequencies of each element
Map<String, Long> frequencies = list.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

//then filter only the inputs which have frequency great than 1
frequencies.entrySet().stream()
        .filter(entry -> entry.getValue() > 1)
        .forEach(entry -> System.out.println(entry.getKey()));

Outputs

Karius
Mo Salah
like image 151
YCF_L Avatar answered Sep 28 '22 06:09

YCF_L