-
stream简介
Java 8 中的 Stream 是对集合(Collection)对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作(aggregate operation),或者大批量数据操作 (bulk data operation)。Stream API 借助于 Lambda 表达式,极大的提高编程效率和程序可读性。
-
stream接口方法
-
集合构建代码
import java.util.*; import java.util.stream.Collectors; public class TestStream { public static void main(String[] args) { List<Map<String, Object>> list1 = new ArrayList<>(); Map<String, Object> map1 = new HashMap<>(4); map1.put("name", "张三"); map1.put("age", 19); map1.put("className", "一班"); map1.put("sex", "男"); list1.add(map1); Map<String, Object> map2 = new HashMap<>(4); map2.put("name", "李四"); map2.put("age", 20); map2.put("className", "一班"); map2.put("sex", "男"); list1.add(map2); Map<String, Object> map3 = new HashMap<>(4); map3.put("name", "王五"); map3.put("age", 19); map3.put("className", "二班"); map3.put("sex", "男"); list1.add(map3); Map<String, Object> map4 = new HashMap<>(4); map4.put("name", "张玲"); map4.put("age", 20); map4.put("className", "二班"); map4.put("sex", "女"); list1.add(map4); Map<String, Object> map5 = new HashMap<>(4); map5.put("name", "张盼盼"); map5.put("age", 19); map5.put("className", "一班"); map5.put("sex", "女"); list1.add(map5); Map<String, Object> map6 = new HashMap<>(4); map6.put("name", "李冰冰"); map6.put("age", 19); map6.put("className", "二班"); map6.put("sex", "女"); list1.add(map6); List<Student> list2 = new ArrayList<>(); Student student1 = new Student("张三", 19, "一班", "男"); list2.add(student1); Student student2 = new Student("李四", 20, "一班", "男"); list2.add(student2); Student student3 = new Student("王五", 19, "二班", "男"); list2.add(student3); Student student4 = new Student("张玲", 20, "二班", "女"); list2.add(student4); Student student5 = new Student("张盼盼", 19, "一班", "女"); list2.add(student5); Student student6 = new Student("李冰冰", 19, "二班", "女"); list2.add(student6); } public static class Student { /** * 姓名 */ private String name; /** * 年龄 */ private int age; /** * 班级 */ private String className; /** * 行别 */ private String sex; public Student() {} public Student(String name, int age, String className, String sex) { this.name = name; this.age = age; this.className = className; this.sex = sex; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getClassName() { return className; } public void setClassName(String className) { this.className = className; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } } }创建流:
stream()
: 从集合创建串行流。parallelStream()
: 从集合创建并行流。
filter(Predicate predicate)
: 应用过滤器,并返回满足条件的元素。//filter过滤 //班级过滤并收集成集合 List<Map<String, Object>> filterList1 = list1.stream() .filter(map -> "一班".equals(map.get("className"))) .collect(Collectors.toList()); List<Student> filterList2 = list2.stream() .filter(student -> "一班".equals(student.getClassName())) .collect(Collectors.toList());
输出结果: [{name=张三, className=一班, age=19, sex=男}, {name=李四, className=一班, age=20, sex=男}, {name=张盼盼, className=一班, age=19, sex=女}]
map(Function<? super T, ? extends R> mapper)
: 应用映射,将元素转换成其他形式或提取信息。//map映射 //获取集合中的姓名列 List<String> mapList1 = list1.stream() .map(map -> String.valueOf(map.get("name"))) .collect(Collectors.toList()); List<String> mapList2 = list2.stream() .map(Student::getName) .collect(Collectors.toList());
输出结果:
[张三, 李四, 王五, 张玲, 张盼盼, 李冰冰]
[张三, 李四, 王五, 张玲, 张盼盼, 李冰冰]mapToInt(ToIntFunction<? super T> mapper)
: 应用映射,将元素转换成int。mapToLong(ToLongFunction<? super T> mapper)
: 应用映射,将元素转换成long。mapToDouble(Function<? super T> mapper)
: 应用映射,将元素转换成double。//mapToInt 映射直接将字段转成int IntStream intStream = list1.stream().mapToInt(map -> Integer.parseInt(String.valueOf(map.get("age")))); int intSum = intStream.sum(); //mapToInt 映射直接将字段转成int LongStream longStream = list1.stream().mapToLong(map -> Long.parseLong(String.valueOf(map.get("age")))); long longSum = longStream.sum(); //mapToInt 映射直接将字段转成int DoubleStream doubleStream = list1.stream().mapToDouble(map -> Double.parseDouble(String.valueOf(map.get("age")))); double doubleSum = doubleStream.sum();
flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)
: 应用映射,但是将每个元素转换成一个流,并把所有流连接成一个流。通过map映射之后是一个流数组,在使用flatMap将留数组编程一个新的流,收集到list集合//flatMap多个数组流连接成一个流 List<String> stringList = Arrays.asList("Java 8 Streams", "are", "really", "easy", "to", "use"); List<String> stringLists = stringList.stream() .map(word -> word.split(" ")) .flatMap(Arrays::stream) .collect(Collectors.toList());
输出结果:[Java, 8, Streams, are, really, easy, to, use]
distinct()
: 返回去除重复元素的流。//distinct字符去重 List<String> list3 = Arrays.asList("Java", "8", "Stream", "are", "are", "really", "easy", "to", "use"); List<String> distinctList = list3.stream() .distinct() .collect(Collectors.toList());
输出结果:[Java, 8, Stream, are, really, easy, to, use]
sorted()
: 返回排序后的流(需要元素实现 接口)。//sorted排序 list<int> List<Integer> intList = Arrays.asList(5, 6, 4, 2, 98, 12); List<Integer> intLists = intList.stream() .sorted() .collect(Collectors.toList());
输出结果:[2, 4, 5, 6, 12, 98]
sorted(Comparator<? super T> comparator)
: 返回根据比较器排序后的流。//sorted排序 List<Object> //年龄排序 List<Map<String, Object>> sortList1 = list1.stream() .sorted(Comparator.comparing(map -> Integer.parseInt(String.valueOf(map.get("age"))))) .collect(Collectors.toList()); List<Student> sortList2 = list2.stream() .sorted(Comparator.comparing(Student::getAge)) .collect(Collectors.toList());
输出结果:[{name=张三, className=一班, age=19, sex=男},
{name=王五, className=二班, age=19, sex=男},
{name=张盼盼, className=一班, age=19, sex=女},
{name=李冰冰, className=二班, age=19, sex=女},
{name=李四, className=一班, age=20, sex=男},
{name=张玲, className=二班, age=20, sex=女}]limit(long maxSize)
: 返回前 n 个元素的流。//limit 获取数据(前n个)(注意下标越界,limit中的值小于集合数量) List<Map<String, Object>> limitList = list1.stream() .limit(2) .collect(Collectors.toList());
输出结果:[{name=张三, className=一班, age=19, sex=男}, {name=李四, className=一班, age=20, sex=男}]
skip(long n)
: 跳过前 n 个元素,返回剩余元素的流。//skip 取数据(剩余)(注意下标越界,skip中的值小于集合数量) List<Map<String, Object>> skipList = list1.stream() .skip(2) .collect(Collectors.toList());
输出结果:[{name=王五, className=二班, age=19, sex=男}, {name=张玲, className=二班, age=20, sex=女}, {name=张盼盼, className=一班, age=19, sex=女}, {name=李冰冰, className=二班, age=19, sex=女}]
peek(Consumer<? super T> action)
: 返回流,同时执行操作。//peek执行操作并返回结果 List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); List<Integer> numberList = numbers.stream() .peek(n -> System.out.print("当前数据" + n)) .map(n -> n * n) .collect(Collectors.toList());
输出结果:当前数据1当前数据2当前数据3当前数据4当前数据5数的平方[1, 4, 9, 16, 25]
forEach(Consumer<? super T> action)
: 对流中的每个元素执行操作。//forEach 循环读取 list1.stream().forEach(System.out::println);
输出结果:
{name=张三, className=一班, age=19, sex=男}
{name=李四, className=一班, age=20, sex=男}
{name=王五, className=二班, age=19, sex=男}
{name=张玲, className=二班, age=20, sex=女}
{name=张盼盼, className=一班, age=19, sex=女}
{name=李冰冰, className=二班, age=19, sex=女}toArray(IntFunction<A[]> generator)
: 返回包含流中元素的数组。//toArray 转数组
List<String> list4 = Arrays.asList("Java8", "Streams", "are", "really", "easy", "to", "use");
String[] toArray = list4.stream().toArray(String[]::new);reduce(T identity, BinaryOperator accumulator)
: 使用给定的初始值和运算符,将流中的元素归约为一个值。//reduce运算 List<Integer> list5 = Arrays.asList(4, 5, 8, 9, 3); Integer reduce = list5.stream().reduce(1, (acc, n) -> acc * n); //1 初始值;acc上次计算结果;n当前值
输出结果:4320
collect(Collector<? super T, A, R> collector)
: 使用收集器,将流中的元素归约为一个结果。//collect收集器 //收集器中实现类型转换 //执行流操作后转list List<Map<String, Object>> filterList1 = list1.stream() .filter(map -> "一班".equals(map.get("className"))) .collect(Collectors.toList()); List<Student> filterList2 = list2.stream() .filter(student -> "一班".equals(student.getClassName())) .collect(Collectors.toList()); //List转Map Map<String, Map<String, Object>> listToMap1 = list1.stream().collect(Collectors.toMap(map -> String.valueOf(map.get("name")), map -> map)); Map<String, Student> listToMap2 = list2.stream().collect(Collectors.toMap(Student::getName, student -> student)); //List转Set Set<Map<String, Object>> mapSet = list1.stream() .filter(map -> "一班".equals(map.get("className"))) .collect(Collectors.toSet()); //收集器中实现分组 //班级分组 Map<Object, List<Map<String, Object>>> classNameGroup1 = list1.stream().collect(Collectors.groupingBy(map -> map.get("className"))); Map<String, List<Student>> classNameGroup2 = list2.stream().collect(Collectors.groupingBy(Student::getClassName));
count()
: 返回流中元素的个数。//count 元素个数 List<String> list6 = Arrays.asList("Java8", "Streams", "are", "really", "easy", "to", "use"); long count = list6.stream().count();
输出结果:7
allMatch(Predicate<? super T> predicate)
: 检查流中的所有元素是否匹配给定的谓词。anyMatch(Predicate<? super T> predicate)
: 检查流中的任何元素是否匹配给定的谓词。noneMatch(Predicate<? super T> predicate)
: 检查流中的所有元素是否都不匹配给定的谓词。//allMatch 全满足条件 List<Integer> list5 = Arrays.asList(4, 5, 8, 9, 3); boolean allMatch = list5.stream().allMatch(n -> n < 10); //anyMatch 部分满足条件 boolean anyMatch = list5.stream().anyMatch(n -> n < 10); //noneMatch 全不满足条件 boolean noneMatch = list5.stream().noneMatch(n -> n < 10);
执行结果:true true false
findFirst()
: 返回流中的第一个元素。findAny()
: 返回流中的任何一个元素。List<String> list6 = Arrays.asList("Java8", "Streams", "are", "really", "easy", "to", "use"); //findFirst 返回第一个元素 String first = list6.stream().findFirst().get(); //findAny 返回任一元素 String any = list6.stream().findAny().get();
输出结果:Java8 Java8
max(Comparator<? super T> comparator)
: 返回流中的最大元素。-
min(Comparator<? super T> comparator)
: 返回流中的最小元素。//max 最大值 Map<String, Object> max = list1.stream().max(Comparator.comparing(map -> Integer.parseInt(String.valueOf(map.get("age"))))).get(); //min 最小值 Map<String, Object> min = list1.stream().min(Comparator.comparing(map -> Integer.parseInt(String.valueOf(map.get("age"))))).get();
输出结果:
{name=李四, className=一班, age=20, sex=男}
{name=张三, className=一班, age=19, sex=男}