Skip to content
Advertisement

Sort List of string arrays by first element

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

Advertisement

Answer

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())
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement