Java使用array.sort()对字符串数组进行排序,就像python使用key=lambda x进行排序一样:

2024-06-09 15:57:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我偶尔学习Java。作为一个有python背景的人,我想知道java中是否存在类似python sorted(iterable, key=function)的东西

对于exmaple,在python中,我可以按元素的特定字符对列表排序,例如

>>> 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'] 

因此a_list首先按升序排序,然后按每个元素的1个索引(第二个)字符排序

我的问题是,如果我想在Java中按特定字符按升序对元素排序,我该如何实现呢

下面是我编写的Java代码:

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

结果是这样的:

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

在这里,我只实现了按升序对数组进行排序。我希望java数组与python列表结果相同

Java对我来说是新的,所以任何建议都将不胜感激

先谢谢你


Tags: 元素排序javasort字符listbobsorted
3条回答

您可以使用Comparator.comparing对列表进行排序

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

如果您想使用Java流API在新列表中进行排序和收集

String [] listSorted =  Arrays.stream(a_list)
                              .sorted(Comparator.comparing(s -> s.charAt(1)))
                              .toArray(String[]::new);

使用自定义比较器比较两个字符串

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

这将通过字符串的第二个字符比较两个字符串

这将导致

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

我看到jaguarkate在输出中被切换。我不确定Python如何排序两个相等的字符串。Arrays.sort进行稳定排序

This sort is guaranteed to be stable: equal elements will not be reordered as a result of the sort.

可以向^{}提供lambda函数。例如,您可以使用:

Arrays.sort(a_list, (String a, String b) -> a.charAt(1) - b.charAt(1));

假设您首先按字母顺序(使用Arrays.sort(a_list))对数组进行排序,这将为您提供所需的结果:

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

相关问题 更多 >