我偶尔会学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对我来说是新的,所以任何建议都会非常感谢。
提前谢谢你。
发布于 2020-08-23 06:53:33
您可以使用Comparator.comparing对列表进行排序。
Arrays.sort(a_list, Comparator.comparing(e -> e.charAt(1)));如果您想使用对新列表进行排序和收集
String [] listSorted = Arrays.stream(a_list)
.sorted(Comparator.comparing(s -> s.charAt(1)))
.toArray(String[]::new);发布于 2020-08-23 06:49:39
您可以向Arrays.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'] https://stackoverflow.com/questions/63544127
复制相似问题