Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the duplicate elements in arraylist and display [closed]

Can anybody help me? I need to write a program, where I have 10 elements in the arraylist and I need to find the how many duplicate values it has and count and display the values as wel.

Ex: say I have

list = {"stack", "overflow", "stack", 
        "yahoo", "google", "msn", 
        "MSN", "stack", "overflow", "user" }

Result should be:

stack = 3
overflow = 2
google = 1
msn = 2
yahoo =1
user = 1
like image 795
Arun Kumar A Avatar asked Oct 18 '12 05:10

Arun Kumar A


1 Answers

Use a HashMap. Here is a simple implementation

List<String> strings = new ArrayList<String>();
strings.put("stack", "overflow", "stack", "yahoo", "google", "msn", "MSN", "stack", "overflow", "user");

Map<String, Integer> counts = new HashMap<String, Integer>();

for (String str : strings) {
    if (counts.containsKey(str)) {
        counts.put(str, counts.get(str) + 1);
    } else {
        counts.put(str, 1);
    }
}

for (Map.Entry<String, Integer> entry : counts.entrySet()) {
    System.out.println(entry.getKey() + " = " + entry.getValue());
}
like image 136
Cory Kendall Avatar answered Nov 15 '22 04:11

Cory Kendall