Skip to content
Advertisement

Java sort string array using Array.sort() like python’s sorted with key=lambda x:

I’m occasionally learning Java. As a person from python background, I’d like to know whether there exists something like sorted(iterable, key=function) of python in java.

For exmaple, in python I can sort a list ordered by an element’s specific character, such as

>>> a_list = ['bob', 'kate', 'jaguar', 'mazda', 'honda', 'civic', 'grasshopper']
>>> s=sorted(a_list) # sort all elements in ascending order first
>>> s
['bob', 'civic', 'grasshopper', 'honda', 'jaguar', 'kate', 'mazda'] 
>>> sorted(s, key=lambda x: x[1]) # sort by the second character of each element
['jaguar', 'kate', 'mazda', 'civic', 'bob', 'honda', 'grasshopper'] 

So a_list is sorted by ascending order first, and then by each element’s 1 indexed(second) character.

My question is, if I want to sort elements by specific character in ascending order in Java, how can I achieve that?

Below is the Java code that I wrote:

import java.util.Arrays;

public class sort_list {
  public static void main(String[] args)
  {
    String [] a_list = {"bob", "kate", "jaguar", "mazda", "honda", "civic", "grasshopper"};
    Arrays.sort(a_list);
    System.out.println(Arrays.toString(a_list));}
  }
}

and the result is like this:

[bob, civic, grasshopper, honda, jaguar, kate, mazda] 

Here I only achieved sorting the array in ascending order. I want the java array as the same as the python list result.

Java is new to me, so any suggestion would be highly appreciated.

Thank you in advance.

Advertisement

Answer

You can use Comparator.comparing to sort the list

Arrays.sort(a_list, Comparator.comparing(e -> e.charAt(1)));

And if you want to sort and collect in the new list using Java Stream API

String [] listSorted =  Arrays.stream(a_list)
                              .sorted(Comparator.comparing(s -> s.charAt(1)))
                              .toArray(String[]::new);
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement