Java 8 引入了流式操作(Stream),通過該操作可以實(shí)現(xiàn)對(duì)集合(Collection)的并行處理和函數(shù)式操作。根據(jù)操作返回的結(jié)果不同,流式操作分為中間操作和最終操作兩種。最終操作返回一特定類型的結(jié)果,而中間操作返回流本身,這樣就可以將多個(gè)操作依次串聯(lián)起來。根據(jù)流的并發(fā)性,流又可以分為串行和并行兩種。流式操作實(shí)現(xiàn)了集合的過濾、排序、映射等功能。
Stream 和 Collection 集合的區(qū)別:Collection 是一種靜態(tài)的內(nèi)存數(shù)據(jù)結(jié)構(gòu),而 Stream 是有關(guān)計(jì)算的。前者是主要面向內(nèi)存,存儲(chǔ)在內(nèi)存中,后者主要是面向 CPU,通過 CPU 實(shí)現(xiàn)計(jì)算。
除了使用Stream 外,還可以使用parallelStream()并發(fā)流,我一般都使用并發(fā)來處理,速度快上很多,但是要注意返回順序。
Stream 操作種類分類兩類:流的中間操作,流的終端操作。
常見的操作有:
filter():對(duì)元素進(jìn)行過濾;
List list=new ArrayList<>();
list.add("1");
list.add("2");
list.add("3");
list.add("4");
list.add("5");
list.add("6");
list.add("1");
list.add("2");
//Filter 過濾
list.stream().filter(e->e.equals("1")).forEach(e-> System.out.println("Filter過濾結(jié)果---e));
sorted():對(duì)元素排序;
//Sorted 排序
list.stream().sorted().forEach(e-> System.out.println("Sorted過濾結(jié)果---------"+e));
list.stream().sorted(Comparator.comparing(String::new)).forEach(e-> System.out.println("Sorted過濾結(jié)果---------"+e));
map():元素的映射;
static class TestEntity {
private String key;
private String value;
public TestEntity(String key, String value) {
this.key = key;
this.value = value;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
}
//map()元素的映射;
List<TestEntity> listMap=new ArrayList<TestEntity>();
listMap.add(new TestEntity("1","a1"));
listMap.add(new TestEntity("2","a2"));
listMap.add(new TestEntity("3","a3"));
//實(shí)際映射到LIST<String>中
listMap.stream().map(e->e.getKey()).collect(Collectors.toList()).forEach(e->System.out.println("map()元素的映射結(jié)果---------"+e));
distinct():去除重復(fù)元素;
//Distinct去除重復(fù)元素
list.stream().distinct().collect(Collectors.toList()).forEach(e-> System.out.println("Distinct去除重復(fù)元素結(jié)果---------"+e));
findFirst():返回第一個(gè)匹配的元素;
//findFirst(): 返回第一個(gè)匹配的元素
Optional<String> s=list.stream().filter(e->e.equals("1")).findFirst();
forEach():對(duì)每個(gè)元素做處理;
這個(gè)上面已經(jīng)又很多案例了
toArray():把元素導(dǎo)出到數(shù)組;
//toArray
String[] strings= list.stream().toArray(String[]::new);
anyMatch():是否有匹配的元素;
//anyMatch() 是否存在 allMatch 是否匹配所有元素 noneMatch 是否未匹配所有元素
boolean exits=list.stream().anyMatch(e->e.equals("1"));
collect():轉(zhuǎn)集合(一般配合map使用)
//.collect收集器 將流中的元素累積到集合中
//toList
List<String> stringList= listMap.stream().map(e->e.getKey()).collect(Collectors.toList());
//收集到String中
String s= listMap.stream().map(e->e.getKey()).collect(Collectors.joining(", "));
//toSet
Set<String> stringSet=listMap.stream().map(e->e.getKey()).collect(Collectors.toSet());
//toCollection 指定到給定的集合
Collection<String> stringArray=listMap.stream().map(e->e.getKey()).collect(Collectors.toCollection(ArrayList::new));
//Counting 計(jì)數(shù)
Long count=listMap.stream().map(e->e.getKey()).collect(Collectors.counting());
//SummingInt 求和
Long countSum=listMap.stream().map(e->e.getKey()).collect(Collectors.summingLong(Long::parseLong));
//groupingBy 根據(jù)流中元素的某個(gè)值對(duì)流中的元素進(jìn)行分組,并將屬性值做為結(jié)果map的鍵
Map<String,List<TestEntity>> map=listMap.stream().collect(Collectors.groupingBy(TestEntity::getKey));
//averagingInt 算平均
Double countAve = listMap.stream().map(e->Double.parseDouble(e.getKey())).collect(Collectors.averagingLong(Double::longValue));
flatMap 扁平化
//flatMap 扁平化
List<String> collect1 = Arrays.stream(strings).map(str->str.split("")).flatMap(Arrays::stream).collect(Collectors.toList());
partitioningBy 收集器
Map<Boolean, List<TestEntity>> map1 = listMap.stream().collect(Collectors.partitioningBy(t->{
int key = Integer.parseInt(t.getKey());
return key>2;
}));
collectingAndThen 轉(zhuǎn)換函數(shù)返回的類型(個(gè)人常用于對(duì)象去重)
//collectingAndThen 轉(zhuǎn)換函數(shù)返回的類型
listMap = listMap.stream().collect(
Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(TestEntity::getKey, (t1, t2) -> {
return t2.compareTo(t1);
}))), ArrayList::new));
listMap.stream().forEach(e -> {
System.out.println("排序后結(jié)果:---" + e.getKey());
});
limit(): 限流操作;
//Limit(): 限流操作 ,返回前N條
list.stream().limit(3).collect(Collectors.toList()).forEach(e-> System.out.println("Limit去限流元素結(jié)果---------"+e));
《未完待續(xù)》