版权声明:本文为博主原创文章,未经博主允许不得转载: https://www.cnblogs.com/zwyu/p/9729309.html
1、流 API
filter():对元素进行过滤
map():将流的元素映射成另一个类型
distinct():去除流中重复的元素
sorted():对元素进行排序
forEach :对流中的每个元素执行某个操作
peek():与forEach()方法效果类似,不同的是,该方法会返回一个新的流,而forEach()无返回
limit():截取流中前面几个元素
skip():跳过流中前面几个元素
toArray():将流转换为数组
reduce():对流中的元素归约操作,将每个元素合起来形成一个新的值
collect():对流的汇总操作,比如输出成List集合
anyMatch():匹配流中的元素,类似的操作还有allMatch()和noneMatch()方法
findFirst():查找第一个元素,类似的还有findAny()方法
max():求最大值
min():求最小值
count():求总数
2、使用案例
(1)查找、匹配、排序、归约操作
import java.awt.print.Book; import java.util.*; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.Comparator.comparing; /** * Created by zwyu on 2018/9/30. */
public class test { public static List<People> getPeople(){ Date dNow = new Date(); Calendar calendar = Calendar.getInstance(); calendar.setTime(dNow); calendar.add(Calendar.DAY_OF_MONTH, -1); Date p1 = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, -2); Date p2 = calendar.getTime(); calendar.add(Calendar.DAY_OF_MONTH, -3); Date p3 = calendar.getTime(); List<People> people = Arrays.asList( new People("张三", 10, p1), new People("李四", 20, p2), new People("老王", 30, p3) ); return people; } public static void test1() { //anyMatch : 任意元素符合筛选条件则返回true
boolean hasMatch = Stream.of("Java", "C#", "PHP", "C++", "Python") .anyMatch(s -> s.equals("Java")); //allMatch : 所有元素符合筛选条件才返回true
boolean hasAllMatch = Stream.of("C#", "C++") .allMatch(s -> s.contains("C#")); //noneMatch : 所有元素的筛选条件为false 才返回true
boolean nonMatch = Stream.of("C#", "C++") .noneMatch(s -> s.contains("C#a")); Optional<String> element = Stream.of("Java", "C#", "PHP", "C++", "Python") .filter(s -> s.contains("C")) // .findFirst() // 获取流中第一个元素
.findAny(); // 获取流中任意元素(其实也是返回第一个元素,能提高并行操作时的性能,推荐使用) // 输出结果:element: C#, hasMatch: true, hasAllMatch: false, nonMatch: true
System.out.println("element: " + element.get() + ", hasMatch: " + hasMatch + ", hasAllMatch: " + hasAllMatch + ", nonMatch: " + nonMatch); } public static void test2() { Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10) .filter(n -> n > 2) // 对元素过滤,保留大于2的元素,剩下3,4,5,6,7,8,9,10,10
.distinct() // 去重,类似于SQL语句中的DISTINCT,剩下3,4,5,6,7,8,9,10
.skip(1) // 跳过前面1个元素
.limit(5) // 返回开头5个元素,类似于SQL语句中的SELECT TOP
.sorted() // 对结果排序,如果元素是类对象则应该使用 sorted(Comparator<? super T> comparator)方法排序
.forEach(System.out::print); // 输出结果:45678
} public static void test3() { List<People> people = getPeople(); long count = people.stream().count(); // reduce:归约操作就是将流中的元素进行合并,形成一个新的值,常见的归约操作包括: 加减乘除、字符串拼接、求最值等功能
Optional<Integer> totalAge = people.stream() .map(People::getAge) .reduce((n, m) -> n * m); Optional<People> maxPeople = people.stream().max(comparing(People::getAge)); // 等价于 Optional<People> maxPeople = people.stream().min(Comparator.comparing(People::getAge).reversed());
Optional<People> minPeople = people.stream().min(comparing(People::getAge)); // 等价于Optional<People> minPeople = people.stream().max(Comparator.comparing(People::getAge).reversed()); // sorted:根据年龄将People对象进行排序, reversed()对排序结果取反: 如之前排序结果是 小到大,加reversed()方法就变为了 大到小
people.stream().sorted(comparing(People::getBirthday, Comparator.nullsFirst(Date::compareTo)).reversed()).forEach(System.out::println); /** * 输出结果: People{name='张三', age=10, birthday=Sat Sep 29 16:45:48 CST 2018} People{name='李四', age=20, birthday=Thu Sep 27 16:45:48 CST 2018} People{name='老王', age=30, birthday=Mon Sep 24 16:45:48 CST 2018} count:3, totalAge: 60, max: People{name='老王', age=30, birthday=Mon Sep 24 16:51:39 CST 2018}, min: People{name='张三', age=10, birthday=Sat Sep 29 16:51:39 CST 2018} */ System.out.println("count:" + count + ", totalAge: " + totalAge.get() + ", max: " + maxPeople.get().toString() + ", min: " + minPeople.get().toString()); } public static void test4() { // 利用reduce的归约操作 实现集合元素的加减乘除、字符串拼接、求最值等功能
String str = Stream.of("A", "B", "C", "D").reduce("-", String::concat); String str2 = Stream.of("A", "B", "C", "D").collect(Collectors.joining("-")); int minValue = Stream.of(1, 2, 3, 4, 5).reduce(Integer.MAX_VALUE, Integer::min); int minValue2 = Stream.of(1, 2, 3, 4, 5).reduce(0, Integer::min); int minValue3 = Stream.of(1, 2, 3, 4, 5).reduce(Integer::min).get(); int minValue4 = Stream.of(1, 2, 3, 4, 5).reduce(Integer::max).get(); int minValue5 = Stream.of(1, 2, 3, 4, 5).reduce(Integer::sum).get(); int minValue6 = Stream.of(1, 2, 3, 4, 5).reduce((n, m) -> n * m).get(); int sum = Stream.of(1, 2, 3, 4).reduce(Integer::sum).get(); int sum2 = Stream.of(1, 2, 3, 4).reduce(7, Integer::sum); /** * 输出结果: str: -ABCD, str2: A-B-C-D, minValue: 1, minValue2: 0, minValue3: 1, minValue4: 5, minValue5: 15, minValue6: 120, sum: 10, sum2: 17 */ System.out.println("str: " + str + ", str2: " + str2 + ", minValue: " + minValue + ", minValue2: " + minValue2 + ", minValue3: " + minValue3 + ", minValue4: " + minValue4 + ", minValue5: " + minValue5 + ", minValue6: " + minValue6 + ", sum: " + sum + ", sum2: " + sum2); } public static void test5() { /** * Collectors 常用的方法有: Collectors.toList(); Collectors.toMap(); Collectors.joining(); Collectors.maxBy(); Collectors.groupingBy(); 等 */ List<People> people = getPeople(); // 求和
long count = people.stream().collect(Collectors.counting()); // 等价于long count = people.stream().count();
Optional<People> optional = people.stream().collect(Collectors.maxBy(comparing(People::getAge))); // 等价于Optional<People> optional = people.stream().max(comparing(People::getAge));
Optional<People> optional2 = people.stream().collect(Collectors.minBy(comparing(People::getAge))); // 等价于Optional<People> optional2 = people.stream().min(comparing(People::getAge));
} public static void main(String[] args) { test1(); test2(); test3(); test4(); } } class People { private String name; private int age; private Date birthday; public People(String name, int age, Date birthday) { this.name = name; this.age = age; this.birthday = birthday; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "People{" +
"name='" + name + '\'' +
", age=" + age +
", birthday=" + birthday +
'}'; } }