版權聲明:本文為博主原創文章,未經博主允許不得轉載: 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 +
'}'; } }