devger
devger

Reputation: 715

How to leave max value in Map of Strings

Hi,

I have list of illogical strings, for example:

Scanner s = new Scanner(
                "m29 523\n" +
                "b34 827\n" +
                "p42 235\n" +
                "b34 294\n" +
                "t78 421\n" +
                "t78 673\n" +
                "c93 173\n" +
                "k46 925\n" +
                "k46 322\n" +
                "x21 644\n");

then I want to break string in two parts - before and after space, eliminate duplicates and leave only max value(after space) among duplicates(b34, t78, k46). I mean such output:

                "m29 523"
                "b34 827"
                "p42 235"
                "t78 673"
                "c93 173"
                "k46 925"
                "x21 644"

As for breaking in two parts and eliminate duplicates I used such code, it's ok for me:

Map<String, ArrayList<String>> list = new HashMap<String, ArrayList<String>>();
        while (s.hasNext()){
            String key = s.next();
            if(!list.containsKey(key));
                list.put(key, new ArrayList<String>());
            list.get(key).add(s.next());
        }
        System.out.println(list);

But don't understand how here I could implement comparison of the second part of string to get max value? Integer.parseInt(list.get(key))?

Upvotes: 1

Views: 183

Answers (2)

Karthik M
Karthik M

Reputation: 89

I don't think you need to complicate with ArrayList.
Just go with Hashmap.
Here is the code to achieve simple.

Map<String, Integer> map = new HashMap<String, Integer>();
        while(s.hasNext()) {
            String key = s.next();
            int value = Integer.parseInt(s.next());
            if(map.containsKey(key)) {
                if(value>map.get(key))
                    map.put(key, value);
            }else map.put(key, value);
        }
        System.out.println("Map="+map);
    }

Upvotes: 1

Micho Rizo
Micho Rizo

Reputation: 1092

how about a simple compare: if the key exist then get the value using the key. Compare the value with the new value using Math.MAX and re-insert using the key. The value will be overwritten by the max value.

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

String key="FOO";
String s[]={"123","012","789"};
for(String numStr: s)
{
    int value = Integer.parseInt(numStr); 
    if(!list.containsKey(key))
        list.put(key, value);
    else 
        list.put(key, Math.max(value, list.get(key)));
}
System.out.println( list.get(key) );

result is 789

Upvotes: 2

Related Questions