user506901
user506901

Reputation: 699

Sorting pairs of numbers according to one value - Java

I'm interested in an efficient way to store pairs of numbers, and to sort them according to a value of one of the numbers. Say I have a list of numbers:

(1, 2), (3, 5), (4, 3), (7, 8)

These pairs need to be stored in some way, then sorted in descending order of the second number, such that the order of these pairs is

(7, 8), (3, 5), (4, 3), (1, 2)

What would be the Java code to achieve this? I'm aware of C++'s std::pair, but I was wondering about the procedure in Java.

Upvotes: 4

Views: 1666

Answers (3)

Vikram Bhat
Vikram Bhat

Reputation: 6246

Make a class pair which implements comparable interface and use arraylist and collections.sort to sort it.

Example :-

public class pair implements Comparable<pair> {

            int a,b;
            @Override
            public int compareTo(pair o) {
                return(o.b-b); 
            }

            public pair(int a,int b) {

               this.a = a ;
               this.b = b;

            }

            public String toString() {
                return "("+a+","+b+")";

            }


            public static void main(String[] args) {

                 ArrayList pairs =  new ArrayList();
                 pairs.add(new pair(4,5));
                 pairs.add(new pair(7,8));
                 pairs.add(new pair(1,3));
                 Collections.sort(pairs);
                 System.out.println("sorted: "+pairs);

            }


        }

Upvotes: 1

stinepike
stinepike

Reputation: 54742

you can use a TreeMap and store the values in a reverse order. so the second values of the paris will be the key of the Map.

Upvotes: 1

Kick
Kick

Reputation: 4923

You can use Multimap to store the pair (1, 2), (3, 5), (4, 3), (7, 8) as key 1 and value 2 for first pair.Then use comparator to sort the map according to the value of map.

Upvotes: 1

Related Questions