Stream流
Java 8 API添加了一种新的机制——Stream(流)。Stream和IO流不是一回事。
- **流式思想:**像生产流水线一样,一个操作接一个操作。
- **使用Stream流的步骤:**数据源→转换成流→操作1→操作2→……
- **数据源(source):**可以是集合、数组等。
Stream操作有两个基础特征:
- Pipelining(流水线):流操作会返回流对象(新的对象),以便后续继续进行流操作。
- **内部迭代:**不需要像for循环或Iterator一样进行显式的迭代。
遍历及过滤集合中的元素
使用传统方式遍历及过滤集合中的元素
1 1 import java.util.ArrayList; 2 2 import java.util.List; 3 3 4 4 /* 5 5 * 使用 传统方式 遍历 及 过滤 集合 6 6 * 需求 : 7 7 * 1、第一步过滤,只需要 以 “张” 开头的名字 8 8 * 2、第二步过滤只需要 ,名字长度为 2 的名字 9 9 * */ 1010 public class Test01Stream { 1111 1212 public static void main(String[] args) { 1313 // 创建一个集合 List , 存储姓名 并根据要求 进行过滤 1414 List<String> nameList = new ArrayList<>(); 1515 nameList.add("张三"); 1616 nameList.add("李四"); 1717 nameList.add("王五"); 1818 nameList.add("赵六"); 1919 nameList.add("田七"); 2020 nameList.add("王八"); 2121 nameList.add("张四"); 2222 nameList.add("张三丰"); 2323 2424 // 使用传统方式进行过滤 2525 2626 // 1、第一步过滤,只需要 以张开头的名字 2727 2828 // 需要 创建一个新的集合 对 第一次过滤之后的 姓名 进行存储 2929 List<String> listA = new ArrayList<>(); 3030 for (String s : nameList) { //使用增强 for 循环 对 集合进行遍历 3131 if (s.startsWith("张")) { 3232 listA.add(s);//将过滤后的结果 添加到新的集合中 3333 } 3434 } 3535 3636 List<String> listB = new ArrayList<>(); 3737 for (String s : listA) { 3838 if (s.length() == 2) { 3939 listB.add(s); 4040 } 4141 } 4242 4343 for (String s : listB) { 4444 System.out.print(s + " ");// 最终过滤结果 张三 张四 4545 } 4646 } 4747 }
使用使用Stream流的方式遍历及过滤集合中的元素
1 1 import java.util.ArrayList; 2 2 import java.util.List; 3 3 4 4 /* 5 5 * 使用Stream流的方式 遍历 并 过滤集合 6 6 * 需求 : 7 7 1、第一步过滤,只需要 以 “张” 开头的名字 8 8 2、第二步过滤只需要 ,名字长度为 2 的名字 9 9 * */ 1010 public class Test02Stream { 1111 1212 public static void main(String[] args) { 1313 // 创建一个集合 List , 存储姓名 并根据要求 进行过滤 1414 List<String> nameList = new ArrayList<>(); 1515 nameList.add("张三"); 1616 nameList.add("李四"); 1717 nameList.add("王五"); 1818 nameList.add("赵六"); 1919 nameList.add("田七"); 2020 nameList.add("王八"); 2121 nameList.add("张四"); 2222 nameList.add("张三丰"); 2323 2424 // 使用 Stream 流的方式 ,对集合进行遍历,并过滤 2525 // 1、第一步过滤,只需要 以 “张” 开头的名字 2626 2727 // 将集合转换为 Stream流, 直接调用Collection接口的一个默认方法 stream 2828 nameList.stream().filter(s->s.startsWith("张")) 2929 .filter(s->s.length()==2) 3030 .forEach(s-> System.out.print(s+" "));// 输出结果 : 张三 张四 3131 } 3232 }