Reputation: 33243
So, I am a newbie in java.
I have a arraylist of Strings.. So.. this array looks like:
[ "foo 123", "bar 124", "foobar 124","foo 125"]
What I want is to remove foo 123
..
Why..
because foo is repeated twice.. and I want to keep the one with the largest count (next to the key)..
My approach has been bit convoluted..
Maintaining a hashmap with key and count. if key is present.. check the value and if value is greater then replace the entry??
I feel like this a clunky way to solve this.. Is there a good way to basically dedupe this list? Thanks
Upvotes: 1
Views: 74
Reputation: 726629
Your approach is very simple - indeed, it's the fastest one asymptotically that you could have, because it is O(N)
in both time and space.
The implementation is very straightforward, too. Use LinkedHashMap
to preserve the insertion order of your keys.
String[] data = new String[] {"foo 123", "bar 124", "foobar 124","foo 125"};
Map<String,Integer> counts = new LinkedHashMap<String,Integer>();
for (String s : data) {
String[] tok = s.split(" ");
Integer count = Integer.valueOf(tok[1]);
if (!counts.containsKey(tok[0]) || counts.get(tok[0]) < count) {
counts.put(tok[0], count);
}
}
for (Map.Entry<String,Integer> e : counts.entrySet()) {
System.out.println(e.getKey() + " " +e.getValue());
}
Upvotes: 1