做個記錄:
Person.java
import lombok.Data;
/**
* @Description:
* @Author: ljf <lin652210786@163.com>
* @Date: 2019/12/02
*/
@Data
public class Person {
private String name;
private int age;
public Person(String name,int age){
this.name = name;
this.age = age;
}
}
新建測試類:test.java
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
/**
* @Description: java8 Stream
* @Author: ljf <lin652210786@163.com>
* @Date: 2019/12/02
*/
public class listtest {
//java8 Stream
public static void main(String[] args) {
List<Person> list = new ArrayList<>();
list.add(new Person("jack", 27));
list.add(new Person("mike", 25));
list.add(new Person("tom", 30));
list.add(new Person("age", 31));
//1.0 根據(jù)條件返回集合
List a = new ArrayList();
//filter(T -> boolean)
a = list.stream().filter(Person -> Person.getAge() > 20).collect(toList());
//2.0 distinct() 去重
List<Person> list1 = new ArrayList<>();
{
list1.add(new Person("Core Java", 200));
list1.add(new Person("Core Java", 200));
list1.add(new Person("Learning Freemarker", 150));
list1.add(new Person("Spring MVC", 300));
list1.add(new Person("Spring MVC", 300));
}
long l1 = list.stream().distinct().count();
System.out.println("No. of distinct books:"+l1);
list1.stream().distinct().forEach(b -> System.out.println(b.getName()+ "," + b.getAge()));
//2.1 去重
List<String> list2 = Arrays.asList("AA", "BB", "CC", "BB", "CC", "AA", "AA");
long l2 = list2.stream().distinct().count();
System.out.println("No. of distinct elements:"+l2);
String output = list2.stream().distinct().collect(Collectors.joining(","));
System.out.println(output);
//2.2 去重
List<Person> list3 = new ArrayList<>();
{
list3.add(new Person("Core Java", 200));
list3.add(new Person("Core Java", 300));
list3.add(new Person("Learning Freemarker", 150));
list3.add(new Person("Spring MVC", 200));
list3.add(new Person("Hibernate", 300));
}
list3.stream().filter(distinctByKey(b -> b.getName()))
.forEach(b -> System.out.println(b.getName()+ "," + b.getAge()));
//3.0 排序
//根據(jù)年齡大小來比較:
/*list = list.stream()
.sorted((p1, p2) -> p1.getAge() - p2.getAge())
.collect(toList());*/
//3.1 簡化排序
/*list = list.stream()
.sorted(Comparator.comparingInt(Person::getAge))
.collect(toList());*/
//4.0 limit(long n)
//返回前 n 個元素
/*list = list.stream()
.limit(2)
.collect(toList());*/
//5.0 skip(long n)
//去除前 n 個元素
/*list = list.stream()
.skip(2)
.collect(toList());*/
// 5.1 先獲取list集合的前兩位元素 在獲取的元素中取出第一位元素
//limit 和 skip 靈活運用
/*list = list.stream()
.limit(2)
.skip(1)
.collect(toList());*/
//6.0 map(T -> R)
//將流中的每一個元素 T 映射為 R(類似類型轉(zhuǎn)換)
/*List<String> newlist =
list.stream().map(Person::getName).collect(toList());*/
//7.0 flatMap(T -> Stream)
//將流中的每一個元素 T 映射為一個流运挫,再把每一個流連接成為一個流
//首先 map 方法分割每個字符串元素损话,但此時流的類型為 Stream镜撩,因為 split 方法返回的是 String[ ] 類型帜慢;
// 所以我們需要使用 flatMap 方法隔披,先使用Arrays::stream將每個 String[ ] 元素變成一個 Stream流,
// 然后 flatMap 會將每一個流連接成為一個流,最終返回我們需要的 Stream
List<String> list4 = new ArrayList<>();
list4.add("aaa bbb ccc");
list4.add("ddd eee fff");
list4.add("ggg hhh iii");
list4 = list4.stream().map(s -> s.split(" ")).
flatMap(Arrays::stream).collect(toList());
//8.0 anyMatch(T -> boolean)
//流中是否有一個元素匹配給定的 T -> boolean 條件
//是否存在一個 person 對象的 age 等于 20:
boolean b = list.stream().anyMatch(person -> person.getAge() == 27);
//9.0 allMatch(T -> boolean)
//流中是否所有元素都匹配給定的 T -> boolean 條件
boolean b1 = list.stream().allMatch(person -> person.getAge() == 27);
//10.0 noneMatch(T -> boolean)
//流中是否沒有元素匹配給定的 T -> boolean 條件
//11.0 findAny() 和 findFirst()
//findAny():找到其中一個元素 (使用 stream() 時找到的是第一個元素;使用 parallelStream() 并行時找到的是其中一個元素)
//findFirst():找到第一個元素
//String b2 = list.stream().findFirst(person -> person);
Person a5 = list.stream().filter(b5 -> "age".equals(b5.getName())).findAny().get();
//添加orElse() 可以在不滿足條件的情況下 自定義返回值 不會跑出異常
Person a6 = list.stream().filter(b5 -> "age11".equals(b5.getName())).findAny().orElse(null);;
System.out.println(a6);
//13.0 計算年齡總和: 其中昔逗,reduce 第一個參數(shù) 0 代表起始值為 0,lambda (a, b) -> a + b 即將兩值相加產(chǎn)生一個新值篷朵。
int sum = list.stream().map(Person::getAge).reduce(0, (a1, c1) -> a1 + c1);
//與之相同:
int sum1 = list.stream().map(Person::getAge).reduce(0, Integer::sum);
//計算年齡總乘積:
int sum2 = list.stream().map(Person::getAge).reduce(1, (a2, c2) -> a2 * c2);
//當(dāng)然也可以
Optional<Integer> sum3 = list.stream().map(Person::getAge).reduce(Integer::sum);
//14.0 count()
//返回流中元素個數(shù)勾怒,結(jié)果為 long 類型
long l3 = list.stream().count();
//15.0 collect()
//收集方法,我們很常用的是 collect(toList())声旺,當(dāng)然還有 collect(toSet()) 等控硼,參數(shù)是一個收集器接口,這個后面會另外講艾少。
Set<Person> set = list.stream().collect(Collectors.toSet());
//16.0 forEach()
//返回結(jié)果為 void,很明顯我們可以通過它來干什么了
list.stream().forEach(System.out ::println);
//向數(shù)據(jù)庫插入新元素:
//list.stream().forEach(PersonMapper::insertPerson);
System.out.println("-------------------");
}
//distinct()功能
private static <T> Predicate<T> distinctByKey(Function<? super T, ?> keyExtractor) {
Map<Object,Boolean> seen = new ConcurrentHashMap<>();
return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}
}