为了账号安全,请及时绑定邮箱和手机立即绑定

Java 使用 Array.sort() 对字符串数组进行排序,就像 python 使用

Java 使用 Array.sort() 对字符串数组进行排序,就像 python 使用

喵喔喔 2023-06-13 11:15:32
我偶尔学习Java。作为一个python背景的人,我想知道sorted(iterable, key=function)java中是否存在类似python的东西。例如,在 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'] Soa_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 对我来说是新手,所以任何建议都将不胜感激。
查看完整描述

3 回答

?
繁星coding

TA贡献1797条经验 获得超4个赞

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

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

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

这将导致

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

我看到了jaguar,并且kate在你的输出中切换了。我不确定 Python 如何排序两个相等的字符串。稳定排序Arrays.sort_

这种排序保证是稳定的:相等的元素不会因为排序而重新排序。


查看完整回答
反对 回复 2023-06-13
?
汪汪一只猫

TA贡献1898条经验 获得超8个赞

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

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

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

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


查看完整回答
反对 回复 2023-06-13
?
红颜莎娜

TA贡献1842条经验 获得超12个赞

您可以向 提供一个 lambda 函数Arrays.sort。对于您的示例,您可以使用:

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


查看完整回答
反对 回复 2023-06-13
  • 3 回答
  • 0 关注
  • 110 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信