Sort pairs of numbers according to a single value - Java

I'm interested in an efficient way to store pairs of numbers and sort them by the value of one of the numbers. Let's say I have a list of numbers:

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

These pairs must be somehow stored and then sorted in descending order of the second number, so the order of these pairs is

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

What will be the Java code for this? I know C ++ std::pair, but I was interested to know about the procedure in Java.

+4
source share
3 answers

Make class pair which implements comparable interfaceand use arraylistand collections.sortto sort.

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);

            }


        }
+1
source

Multimap (1, 2), (3, 5), (4, 3), (7, 8) 1 2 . comparator .

+1

you can use TreeMap and save the values ​​in reverse order. therefore, the second value of Paris will be the card key.

+1
source

Source: https://habr.com/ru/post/1525402/


All Articles