I want to sort a list of string arrays by first element in each array element of same list, in reverse order, so 2, 1, 0
Here's what i tried so far:
List<String[]> array = new ArrayList<>();
String[] arr1 = {"0", "1/1"};
String[] arr2 = {"1", "1/2"};
String[] arr3 = {"2", "1/4"};
array.add(arr1);
array.add(arr2);
array.add(arr3);
Comparator<String[]> byFirstElement =
(String[] array1, String[] array2) -> Integer.parseInt(array1[0]) -
Integer.parseInt(array2[0]);
List<String[]> result = array.stream()
.sorted(array,byFirstElement) // error here
.collect(Collectors.toList());
The problem is that at sorted line i have an error highlighted, saying: "sorted(java.util.List, java.util.Comparator
Stream.sorted()
takes a comparator (in addition to the overload that takes no argument). So all you need is ...sorted(byFirstElement)...
(the stream sorts its elements)
Note that your comparison logic won't sort in descending order, so you either need to change it to
Comparator<String[]> byFirstElement =
(array1, array2) -> Integer.parseInt(array2[0]) - Integer.parseInt(array1[0]);
//reversed
or reverse it when calling sorted()
:
....sorted(byFirstElement.reversed())
You can simplify your code with the Comparator.comparing
method as follows:
List<String[]> list = List.of(
new String[]{"0", "1/1"},
new String[]{"1", "1/2"},
new String[]{"2", "1/4"});
List<String[]> sorted = list.stream()
.sorted(Comparator.comparing(
arr -> Integer.parseInt(arr[0]), Comparator.reverseOrder()))
.collect(Collectors.toList());
// output
sorted.stream().map(Arrays::toString).forEach(System.out::println);
Output:
[2, 1/4]
[1, 1/2]
[0, 1/1]
See also:
• How to sort by a field of class with its own comparator?
• Sorting 2D array of strings in alphabetical order
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.