Skip to content

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"};

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.



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 =
                              .sorted(Comparator.comparing(s -> s.charAt(1)))
9 People found this is helpful