简体   繁体   中英

finding and replacing duplicates in java

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

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

Demo on ideone .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM