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"
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. }
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
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