9

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"

6
  • First of all, describe algorythm you want to apply to get duplicated words list Commented May 27, 2018 at 7:36
  • you can't use that method unless you remove the searched string element first, then use "contains", then add it back Commented May 27, 2018 at 7:38
  • karius and Mo Salah are duplicated (but not only karius) Commented May 27, 2018 at 7:50
  • Karius shouldn't be mentioned in any any example. Commented May 27, 2018 at 8:10
  • You had some syntax error in your error, I have modified your code. Commented May 28, 2018 at 15:06

8 Answers 8

9

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
Sign up to request clarification or add additional context in comments.

Comments

6

Try this working code:

ArrayList<String> list = new ArrayList<String>();
        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");

        Set<String> s = new HashSet<String>();

        for(String name : list) {
            if(s.add(name) == false)
                System.out.println(name + "is duplicated");
        }

Output:

Kariusis duplicated
Mo Salahis duplicated

Comments

3

You can use lastIndexOf to check for duplicates

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

Note that if you have triplicates or more this will print "xxx is duplicated" several times for the same name but you only asked to check for duplicates so this solution should be enough.

Comments

1

If you want to reduce some time complexity at the cost of O(n) space, you can use a Set

Set<String> set = new HashSet<>();
for(int i =0; i < list.size(); i++) {
    if (set.contains(list.get(i))) {
         System.out.println(list.get(i)+" is duplicated");
    } else set.add(list.get(i));
}

1 Comment

Set::add returns a boolean to specify if the record was added or not. Set::contains wouldn't be necessary.
0

You can use two sets. This is bettwer for performance O(n), because you have to loop an array only once, but less effective with the memory O(n):

public static Set<String> getDuplicates(List<String> list) {
    Set<String> res = new HashSet<>();
    Set<String> existed = new HashSet<>();

    list.forEach(str -> {
        if (!existed.add(str))
            res.add(str);
    });

    return res;
}

Another option, is to use streams:

public static Set<String> getDuplicates(List<String> list) {
    return list.stream().filter(i -> Collections.frequency(list, i) > 1).collect(Collectors.toSet());
}

5 Comments

why does he need to use two sets? one hashset is enough - for each element in the list: he takes an element, checks whether it has been added to the set before, if yes, then output it, otherwise put it into hashset
@mangusta In case print to the console is what you need - yes, one set is enough. But this is not my style, I prefer to prepare data and then do what I want. This method retrieved duplicated and does not responsible for output to console.
@shinjw No :-). Try to think why.
I'd recommend mentioning the time complexity for the stream solution.
Set<String> set = new HashSet<>(); return list.filter(v -> !set.add(v)).collect(Collectors.toSet()); Would be more optimal in runtime.
0

you can follow this Find the duplicate elements in arraylist and display

 public static void main(String[] args) {
    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");

    HashMap<String, Integer> map = new LinkedHashMap<>(); // If you want insertion order same

    list.forEach((string) -> {
        if (map.containsKey(string)) {
            map.put(string, map.get(string) + 1);
        } else {
            map.put(string, 1);
        }
    });
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        String key = entry.getKey();
        Integer value = entry.getValue();
        if (value > 1) {
            System.out.println(key + " is duplicated");
        }
    }
}

Comments

0
List<String> newList = new ArrayList();

Java 8:

oldList.forEach( {

    if (newList.contains(e)) {
        Sytem.out.println(e+" is duplicated");
    } else {
        newList.add(e);
    }
});

Java 7: you can use customised for loop to get each from oldList.

Comments

0
import java.util.ArrayList;

import java.util.HashMap;

public class CollectionsEx2 {

public static void main(String[] args) {
    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");
    
    HashMap<String,Integer> hm = new HashMap<String,Integer>();
    for(String i: list) {
        if (hm.containsKey(i)) hm.put(i, hm.get(i)+1);
        else hm.put(i, 1);
    }
    System.out.println("HashMap:" + hm);

}

}

O/p: HashMap:{Firmino=1, Sagio Mane=1, Lovren=1, Karius=2, Steven Gerrard=1, Mo Salah=2}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.