我偶尔学习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 对我来说是新手,所以任何建议都将不胜感激。
繁星coding
汪汪一只猫
红颜莎娜
相关分类