I have the following string array: "0 11", "22 34", "5 14", "22 13"... How do I sort it so that both numbers are in increasing order: "0 11", "5 14", "22 13", "22 34"?
-
3I don't understand what you mean. In your example, both numbers are not in increasing order; for instance, 14 comes before 13.Sam Estep– Sam Estep2016-11-27 12:34:51 +00:00Commented Nov 27, 2016 at 12:34
-
2In general, storing two informations in a String is a bad idea. Parse the strings and transform them into objects with two int properties.JB Nizet– JB Nizet2016-11-27 12:35:39 +00:00Commented Nov 27, 2016 at 12:35
-
Your post needs editing for clarity of expression; as it stands, it's not clear what you are asking.nyedidikeke– nyedidikeke2016-11-27 12:44:22 +00:00Commented Nov 27, 2016 at 12:44
-
do you need something like` "0 11", "5 14", "13 22", "22 34"` ?Real73– Real732016-11-27 12:46:42 +00:00Commented Nov 27, 2016 at 12:46
Add a comment
|
3 Answers
You just need to implement an appropriate Comparator. Like that:
public static void main(String[] args) {
String [] ar = {"0 11", "22 34", "5 14", "22 13"};
Arrays.sort(ar, new Comparator<String>() {
@Override
public int compare(String o1, String o2) {
String [] value1 = o1.split(" ");
String [] value2 = o2.split(" ");
Integer o1First = Integer.valueOf(value1[0]);
Integer o1Second = Integer.valueOf(value1[1]);
Integer o2First = Integer.valueOf(value2[0]);
Integer o2Second = Integer.valueOf(value2[1]);
if (!o1First.equals(o2First))
return o1First.compareTo(o2First);
return o1Second.compareTo(o2Second);
}
});
System.out.println(Arrays.toString(ar));
}
Comments
Use Collections.sort(List, Comparator) Try this,
Collections.sort(yourList, new Comparator<String>() {
@Override
public int compare(String s1, String s2) {
String[] split1 = s1.split(" ");
String[] split2 = s2.split(" ");
int n = split1[1].compareTo(split2[1]);
if (n == 0) {
return Integer.valueOf(split1[0]).compareTo(
Integer.valueOf(split2[0]));
}
return n;
}
});
Comments
A little less verbose:
Arrays.sort(ar, Comparator.comparingInt((String s) -> Integer.parseInt(s.split(" ")[0]))
.thenComparingInt((String s) -> Integer.parseInt(s.split(" ")[1])));
Unfortunately Java does not currently have built in support for tuple value types. Otherwise the code could be shorter.