0

I have to take the input of some integer pairs. After that sort them and I've to do some arithmetic operation with the pair. I used TreeMap as it allows sorting too but it fails when I have the duplicate key. So, what collection/method should I use in my program? Please suggest.

TreeMap<Integer, Integer> h = new TreeMap<Integer, Integer>(Collections.reverseOrder());
for(int i=0; i<n; i++){
    String ll[] = br.readLine().split(" ");
    h.put(Integer.parseInt(ll[0]), Integer.parseInt(ll[1]));            
}
Abdullah Khan
  • 12,010
  • 6
  • 65
  • 78

2 Answers2

1

Instead of using a TreeMap, you can define your own pair class, put the objects in an ArrayList and sort the elements based on the key.

class Pair{
 final int first;
 final int second;
 .... constructor, getters 
}

And then sort it using Collections.sort

Collections.sort(pairs, Pair::getFirst);
Sleiman Jneidi
  • 22,907
  • 14
  • 56
  • 77
0

Why not implementing your own class?

Such as

class Pair implements Comparable {
    int a, b;
    // Implement operations you want, compareTo() method
}

The you can store these Pair objects in ArrayList<Pair> and use Collections.sort() method to sort the data way you want.

Hyun I Kim
  • 589
  • 1
  • 3
  • 14