如何按排序顺序查找以小写“a”开头的前三个字符串

Java 8 流 API /


a如何查找按排序顺序以小写字母开头的前三个字符串。如何使用 打印结果System.out.println()。


List<String> myList =


   Arrays.asList("A1", "a2", "b1", "c2", "A2", "a3", "c2", "A3", "c2", "a1", "a4", "a6");


       myList.stream().filter(s -> s.startsWith("a"))


             .map(String::toLowerCase)


             .sorted()


             .forEach(s ->System.out.println("Filtered value: " + s)); 

a如何只打印按排序顺序以小写字母开头的前三个字符串?


请帮忙

& 在这种情况下:我不明白嵌套的这个任务:如何只打印前三个字符串,它们按排序顺序以小写 a 开头?


公共课任务{


public static void main(String[] args){


final List<String> myList1 =

    Arrays.asList("c1", "b2", "G3", "g4", "b1",

                  "b3", "G5", "g3", "b5", "e2", "b8", "b2",

                  "g8", "i9", "b10", "j6", "s2", "g2", "B9",

                  "B1", "g7", "b8", "N7", "e9");

final List<String> myList2 =

    Arrays.asList("c1", "b2", "G3", "g4", "b1",

                  "b3", "G5", "g3", "b5", "e2", "b8", "b2",

                  "g8", "i9", "b10", "j6", "s2", "g2", "B9",

                  "B1", "g7", "b8", "N7", "e9");


List<List<String>> nestedList = new ArrayList<>();

nestedList.add(myList1);

nestedList.add(myList2);}}


杨__羊羊
浏览 114回答 3
3回答

Cats萌萌

这似乎有效 - 需要告诉列表您正在使用什么类型的对象List<String> myList = Arrays.asList("A1", "a2", "b1", "c2", "A2",&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;"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因此无需转换为小写。

jeck猫

您可以.limit(3)在排序后添加到您的流中。需要输入列表才能使用 String 方法,除非您希望将结果转换为小写,否则List<String>不需要。toLowerCaseList<String> myList = List.of(&nbsp; &nbsp; "A1", "a2", "b1", "c2", "A2", "a3", "c2", "A3", "c2", "a1", "a4", "a6");myList.stream().filter(s -> s.charAt(0) == 'a').sorted().limit(3)&nbsp; &nbsp; .forEach(s -> System.out.println("Filtered value: " + s));更新:对于从每个字符串的索引 1 开始的数字排序:Comparator<String> comparator = Comparator.comparing(&nbsp; &nbsp; s -> Integer.parseInt(s.substring(1)));myList.stream().filter(s -> s.charAt(0) == 'a').sorted(comparator).limit(3)&nbsp; &nbsp; .forEach(s -> System.out.println("Filtered value: " + s));

largeQ

请找到以下相同的代码:List<String>&nbsp;myList&nbsp;=&nbsp;Arrays.asList("A1",&nbsp;"a2",&nbsp;"b1",&nbsp;"c2",&nbsp;"A2",&nbsp;"a3",&nbsp;"c2",&nbsp;"A3",&nbsp;"c2",&nbsp;"a1",&nbsp;"a4",&nbsp;"a6"); &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;myList.stream().filter(x->&nbsp;x.startsWith("a")).sorted().limit(3).forEach(System.out&nbsp;::&nbsp;println);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java