0

I have written the following code and got the output. import java.util.ArrayList;

public class DuplicatesinArrayList {

    public static void main(String[] args) {

        ArrayList <String> al = new ArrayList<>();
        al.add("Soumen");
        al.add("Rahul");
        al.add("Soumen");
        al.add("Ram");
        al.add("Rahul");
        al.add("Rahul");
        al.add("Rahul");
        al.add("Ram");
        al.add("Ram");
        al.add("Ram");
        al.add("Ram");

        for (int i = 0; i < al.size(); i++) {  
            int ctr = 0;
            for (int j = 0; j < al.size(); j++) {
                if(al.get(i).equals(al.get(j)))
                    ctr++;
            }
            System.out.println(al.get(i)+" present " + ctr + " times"); 
        }
    }
}

The result is as follows:

Soumen present 2 times
Rahul present 4 times
Soumen present 2 times
Ram present 5 times
Rahul present 4 times
Rahul present 4 times
Rahul present 4 times
Ram present 5 times
Ram present 5 times
Ram present 5 times
Ram present 5 times

I want for each word there should be one result. Can anyone help?

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373

1 Answers1

2

You can use a map for that

Map<String, Integer> map = new HashMap<>();
for (String s : al) {
    if (map.containsKey(s)) map.put(s, map.get(s) + 1);
    else map.put(s, 1);
}

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    System.out.println(entry.getKey()+" present " + entry.getValue() + " times");
}

Alternatively you can use java8 streams:

al.stream().collect(groupingBy(o -> o, counting())).forEach((name, count) -> System.out.println(name + " present " + count + " times"));
msumera
  • 160
  • 1
  • 9