trx
trx

Reputation: 2157

Treemap getting maximum of the values associated with each key

In a treemap,I have each key having multiple values. I have to get only the maximum of each values associated with the key. Can anyone help to do that..

  BufferedReader reader = new BufferedReader(new FileReader("E:\\book\\geneanno.txt"));
  Map<String, String> map = new TreeMap<String,String>();
  String currentLine;
  while ((currentLine = reader.readLine()) != null){
        String[] pair  = currentLine.split("\\s+");
        key = pair[12];
        value = pair[4]+" ";
        if(map.containsKey(key)){
            value +=  map.get(key);
        } 
            map.put(key,value);

The output I get is like this

Key: A1CF Values : 9168 7541 1478 1001

Key: B547 Values : 1247 7841 1247 3471

But I have to get Output only like this

Key: A1CF Values : 9168

Key: B547 Values : 7841

Upvotes: 0

Views: 672

Answers (2)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41210

Instead of concatenating all values in String, you could use TreeSet where elements will be ordered using their natural ordering.

Map<String,Set<Integer>> map = TreeMap<String,TreeSet<Integer>>();

And while iterating you could get the maximum value by TreeSet#last(), as your value Set is naturally ordered.

Upvotes: 2

Kevin
Kevin

Reputation: 3509

In addition to Subhrajyoti's answer.

You can also do the following:

Map<String, Integer> map = new TreeMap<String,Integer>();

if(map.get(token) == null)
{
   map.put(token,value)
}
else if(map.get(token) < newValue)
{
   map.put(token,newValue)
}

Essentially what happens is you will store only the greatest value for every key/ value pair.

This solution is just a tad bit more memory efficient.

Upvotes: 1

Related Questions