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]));            
}
1

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.