package com.example.ss_0203_array.test.test_0830; import java.util.ArrayList; import java.util.Collections; import java.util.stream.Stream; public class test3 { public static void main(String[] args) { /** * 按照下面的要求完成集合的创建和遍历 * * - 创建一个集合,存储多个字符串元素 * - 把集合中所有以"张"开头的元素存储到一个新的集合 * - 把"张"开头的集合中的长度为3的元素存储到一个新的集合 * - 遍历上一步得到的集合 */ ArrayList<String> list = new ArrayList<>(); Collections.addAll(list,"张三丰","张无忌","张翠山","王二麻子","张良","谢广坤"); ArrayList<String> result = new ArrayList<>(); for (String l : list) { if(l.startsWith("张")){ result.add(l); } } System.out.println(result); ArrayList<String> result2 = new ArrayList<>(); for (String s : result) { if (s.length() == 3){ result2.add(s); } } System.out.println(result2); System.out.println("-------------------"); System.out.println("---------- 使用Stream流示例代码----------"); ArrayList<String> result3 = new ArrayList<>(); list.stream() .filter(s -> s.startsWith("张")) .filter(s -> s.length() == 3) .forEach(s->result3.add(s)); System.out.println(result3); } }
标签:java,Stream,ArrayList,练习,System,集合,println,out From: https://www.cnblogs.com/pangchunlei/p/17666568.html