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
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());
}
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