3 回答
TA贡献1805条经验 获得超9个赞
这似乎有效 - 需要告诉列表您正在使用什么类型的对象
List<String> myList = Arrays.asList("A1", "a2", "b1", "c2", "A2",
"a3", "c2", "A3", "c2", "a1", "a4", "a6");
myList.stream().filter(s -> s.startsWith("a")).sorted().limit(3)
forEach(s ->System.out.println("Filtered value: " + s));
此外,由于您只需要小写,a因此无需转换为小写。
TA贡献1909条经验 获得超7个赞
您可以.limit(3)在排序后添加到您的流中。需要输入列表才能使用 String 方法,除非您希望将结果转换为小写,否则List<String>不需要。toLowerCase
List<String> myList = List.of(
"A1", "a2", "b1", "c2", "A2", "a3", "c2", "A3", "c2", "a1", "a4", "a6");
myList.stream().filter(s -> s.charAt(0) == 'a').sorted().limit(3)
.forEach(s -> System.out.println("Filtered value: " + s));
更新:对于从每个字符串的索引 1 开始的数字排序:
Comparator<String> comparator = Comparator.comparing(
s -> Integer.parseInt(s.substring(1)));
myList.stream().filter(s -> s.charAt(0) == 'a').sorted(comparator).limit(3)
.forEach(s -> System.out.println("Filtered value: " + s));
TA贡献2039条经验 获得超7个赞
请找到以下相同的代码:
List<String> myList = Arrays.asList("A1", "a2", "b1", "c2", "A2", "a3", "c2", "A3", "c2", "a1", "a4", "a6"); myList.stream().filter(x-> x.startsWith("a")).sorted().limit(3).forEach(System.out :: println);
添加回答
举报