Java中Collection类排序失效,需按三元组[g,x,y]的g值排序求助
g Got it, let's break down why your Collections.sort(listToSort) isn't sorting your [g,x,y] triples by the first value g as expected, and fix it step by step.
The Root Problem
By default, Collections.sort() uses the natural ordering of the elements in your list. If your triples are:
- A custom class (like
Triple), the JVM has no idea how to compare two instances unless you explicitly define the ordering. - A
Listor array type (e.g.,List<List<Integer>>), the default sort will compare the entire sequence of elements, not just the first oneg.
So we need to tell the sort method exactly how to prioritize the g value.
Solution 1: Make Your Custom Triple Class Comparable
If you're using a custom class for your triples (e.g., class Triple { int g; int x; int y; }), implement the Comparable interface to define natural ordering around g:
class Triple implements Comparable<Triple> { private int g; private int x; private int y; // Constructor, getters, setters here @Override public int compareTo(Triple other) { // Sort by g in ascending order // Reverse the values (other.g - this.g) for descending order return Integer.compare(this.g, other.g); // If g is a String, use: // return this.g.compareTo(other.g); } }
Now Collections.sort(listToSort) will work exactly as you want—it uses the compareTo method you defined to sort by g.
Solution 2: Use a Custom Comparator (No Class Modifications Needed)
If you can't or don't want to change the triple class, pass a custom Comparator directly to Collections.sort(). This is great for one-off or dynamic sorting needs.
For Custom Triple Classes
// Pre-Java 8 anonymous class Collections.sort(listToSort, new Comparator<Triple>() { @Override public int compare(Triple t1, Triple t2) { return Integer.compare(t1.getG(), t2.getG()); } }); // Java 8+ lambda (cleaner) Collections.sort(listToSort, (t1, t2) -> Integer.compare(t1.getG(), t2.getG())); // Even shorter with method references Collections.sort(listToSort, Comparator.comparingInt(Triple::getG));
For List/Array-Based Triples (e.g., List<List<Integer>>)
If your list contains List<Integer> elements representing [g,x,y], target the first index directly:
Collections.sort(listToSort, (triple1, triple2) -> Integer.compare(triple1.get(0), triple2.get(0)) ); // Or with method references Collections.sort(listToSort, Comparator.comparingInt(triple -> triple.get(0)));
Quick Check
Double-check that:
- You're accessing the correct
gvalue (no typos in getter methods or index positions). - The data type of
gmatches the comparison logic (e.g., useString.compareTo()for String values instead ofInteger.compare()).
That should get your list sorted exactly by the g value as intended!
内容的提问来源于stack exchange,提问作者Rima Sur

