【发布时间】:2020-08-23 15:02:59
【问题描述】:
我偶尔会学习 Java。作为一个python背景的人,我想知道java中是否存在类似sorted(iterable, key=function)的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']
所以a_list首先按升序排序,然后按每个元素的第一个索引(第二个)字符。
我的问题是,如果我想在 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 对我来说是新手,所以任何建议都将受到高度赞赏。
提前谢谢你。
【问题讨论】:
标签: java python arrays sorting