简体   繁体   中英

Java - sorting a list of lists with 2 items by a second item

I have code in Python:

self.sousedi_sorted = sorted(sousedi, key = lambda s: s[1])

and I need to write the same thing in Java.

I have a list of tuples (or lists) with two items (index and score) and I need to sort the lists by score - second item. I've read about Collections.sort and Arrays.sort, but I still don't know, how to make it.

Thank you for your answer.

Instead of a lambda expression, Java uses a Comparator<T> class. The <T> means that it is generic - when you implement a comparator, you specify what type you're comparing.

You can implement a Comparator as follows:

// This defines a class, MyComparator, that will compare objects
// of type SomeClass (because that's what's in the angle brackets)
public class MyComparator implements Comparator<SomeClass> {
    @Override
    public int compare(SomeClass o1, SomeClass o2) {
        // This method compares o1 and o2.
        // If o1 is "greater than" o2, it returns a positive number.
        // If they are equal, it returns 0.
        // If o1 is "less than" o2, it returns a negative number.

        // For example:
        return o1.someInt - o2.someInt;
    }
}

From the documentation :

int compare(T o1, T o2)
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.

Then, you can use Collections.sort(listVariableName, new MyComparator()) to sort the list:

ArrayList<SomeClass> someListOfThings = new ArrayList<SomeClass>();
// add things to the list with someListOfThings.add(...)
Collections.sort(someListOfThings, new MyComparator());
// list is now sorted according to the `compare` method in MyComparator

So in your case you might have:

class MyObject {
    public int index;
    public int score;
}
class MyObjectScoreComparator implements Comparator<MyObject> {
    public int compare(MyObject o1, MyObject o2) {
        return o1.score - o2.score;
    }
}

and then use sort .

You'll want to use a Comparator . It lets you define a way to compare two objects, which may then be used to sort a collection of those objects with Collections.sort.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM