Stream简介
1、Java 8引入了全新的Stream API。这里的Stream和I/O流不同,它更像具有Iterable的集合类,但行为和集合类又有所不同。
2、stream是对集合对象功能的增强,它专注于对集合对象进行各种非常便利、高效的聚合操作,或者大批量数据操作。
3、只要给出需要对其包含的元素执行什么操作,比如 “过滤掉长度大于 10 的字符串”、“获取每个字符串的首字母”等,Stream 会隐式地在内部进行遍历,做出相应的数据转换。
为什么要使用Stream
1、函数式编程带来的好处尤为明显。这种代码更多地表达了业务逻辑的意图,而不是它的实现机制。易读的代码也易于维护、更可靠、更不容易出错。
package com.lxg.springboot.test;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* @author 小石潭记
* @date 2020/7/7 20:13
* @Description: ${todo}
*/
public class Test {
public static void main(String[] args) {
List<User> list = new ArrayList<>();
list.add(new User(2, "小皇1", 20));
list.add(new User(3, "小皇1", 30));
list.add(new User(4, "小皇1", 40));
List<User> list1 = new ArrayList<>();
list1.add(new User(1, "小皇1", 10));
list1.add(new User(2, "小皇1", 20));
list1.add(new User(3, "小皇1", 30));
list1.add(new User(4, "小皇1", 40));
// 需求:给list里面user对象age > 20 添加备注信息:大龄剩女
// 以前的写法
List<User> userList = new ArrayList<>();
for (User user: list) {
if (user.getAge() > 20){
user.setRemark("大龄剩女");
}
userList.add(user);
}
System.out.println("userList:" + userList);
// 使用java8的新特性,stream的方式
// 这里直接操作list里面的对象,返回值还是该list
list.stream()
.filter(e -> e.getAge() > 20)
.forEach(e -> e.setRemark("大龄剩女"));
System.out.println("list:" + list);
list.stream()
.forEach(e -> {
if (e.getAge() > 20) {
e.setRemark("大龄剩女");
}
});
System.out.println("list:" + list);
// 使用map会生成一个新的list
list1.stream()
.map(e -> {
if (e.getAge() > 20) {
e.setRemark("大龄剩女");
}
return e;
})
.collect(Collectors.toList());
System.out.println("list1:" + list1);
}
static class User {
private int id;
private String name;
private int age;
private String remark;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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 getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public User(){
}
public User(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
", remark='" + remark + '\'' +
'}';
}
}
}
2、高端
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
import java.util.function.Function;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.*;
/**
* @author liujiang
* @version v1.0
* @description 本类主要是用于归纳总结java8 Stream的使用方式,后续会继续补充
* @since 2019/8/5 22:40
*/
public class Lambda {
public static void main(String[] args) {
readMeFirst();
final List<Cat> catList = initList();
// 1. filter(Predicate<? super T> predicate) 过滤年龄小于等于3的猫咪
List<Cat> ageLessThanThreeList = catList.parallelStream().filter(cat -> cat.getAge().compareTo(3) <= 0).collect(toCollection(LinkedList::new));
System.out.println("------ filter line ------");
ageLessThanThreeList.parallelStream().forEach(System.err::println);
// 2. map(Function<? super T, ? extends R> mapper) 将英文名称全部大写
List<String> upperCaseEnNameList = catList.parallelStream().map(cat -> cat.getEnName().toUpperCase()).collect(Collectors.toList());
System.out.println("------ map line -------");
upperCaseEnNameList.parallelStream().forEach(enName -> {
System.err.print(enName + " ");
});
System.out.println();
// 3. mapToInt(ToIntFunction<? super T> mapper) 对年龄求和
int sumAge = catList.parallelStream().mapToInt(Cat::getAge).sum();
System.out.println("------ mapToInt line -----");
System.err.println(sumAge);
// 4. flatMap(Function<? super T, ? extends Stream<? extends R>> mapper) 层级结构扁平化
List<List<Integer>> flatMapList = flatMapInitList();
List<Integer> numberList = flatMapList.parallelStream().flatMap(itemList -> itemList.parallelStream()).collect(toList());
System.out.println("------ flatMap line ------");
numberList.parallelStream().forEach(item -> {
System.err.print(item.toString() + " ");
});
// 5. distinct 去重
List<Cat> dupCatList = dupCatInitList();
List<Cat> duplicateCatList = dupCatList.parallelStream().distinct().collect(toList());
System.out.println();
System.out.println("----- distinct for cat line (error) -------");
duplicateCatList.stream().forEach(cat -> {
// 因为没有重写hashCode 及 equals方法,所以得到的是两个Cat对象
System.err.println(cat.toString());
});
// case two, 实现过滤去重
List<Integer> dupIntegerLit = dupIntegerInitList();
List<Integer> duplicateIntegerList = dupIntegerLit.parallelStream().distinct().collect(toList());
System.out.println("------ distinct for Integer line (right) -----");
duplicateIntegerList.parallelStream().forEach(System.out::print);
System.out.println();
// 6. sorted --> no args
List<Integer> orderAgeList = catList.parallelStream().map(Cat::getAge).sorted().collect(toList());
System.out.println("------ sorted line (no args) ------");
orderAgeList.stream().forEach(System.out::print);
System.out.println();
System.out.println("attention:并行流会影响排序,需要特别注意!并行流结果为:");
orderAgeList.parallelStream().forEach(System.out::print);
// sorted(Comparator<? super T> comparator) --> has args [reverse order]
List<Cat> orderedAgeOfCatList = catList.parallelStream().sorted(Comparator.comparing(Cat::getAge).reversed()).collect(toList());
/*
等效于:
List<Cat> orderedAgeOfCatList = catList.parallelStream().sorted(Collections.reverseOrder(Comparator.comparing(Cat::getAge))).collect(toList());
即:Comparator.comparing(Cat::getAge).reversed() = Collections.reverseOrder(Comparator.comparing(Cat::getAge))
*/
System.out.println();
System.out.println("-------- sorted line (has args)------");
orderedAgeOfCatList.stream().forEach(cat -> {
System.err.println(cat.toString());
});
// 使用java8 list.sort(Comparator<? super E> c)
catList.sort(Comparator.comparing(Cat::getAge).thenComparing(Cat::getCnName).reversed());
System.out.println("------- list.sort() -------");
catList.stream().forEachOrdered(System.out::println);
/*
总结:
1. 无参的sorted()是对某一项的排序,默认返回natural order,返回的是Stream<T>
2. 带参的sorted(Comparator<? super T> comparator)可对实体类中的某项排序,默认natural order,可通过reversed()方法倒序,返回的是实体类的集合.
3. 亦可使用java8 新的排序方式 list.sort(Comparator<? super E> c),配合Comparator进行排序
*/
// 7. limit(long maxSize)
List<Cat> limitCatList = catList.stream().limit(2).collect(toList());
System.out.println("------ limit line ------");
limitCatList.stream().forEach(cat -> {
System.err.println(cat.toString());
});
// 8. skip(long n)
List<Cat> skipCatList = catList.stream().skip(1).collect(toList());
System.out.println("------ skip line ------");
skipCatList.parallelStream().forEach(cat -> {
System.err.println(cat.toString());
});
// 9. min(Comparator<? super T> comparator) 最小的
Cat minAgeOfCat = catList.parallelStream().min(Comparator.comparing(Cat::getAge)).get();
System.out.println("------ min line ------");
System.err.println(minAgeOfCat.toString());
// 10. max(Comparator<? super T> comparator) 最大的
Cat maxAgeOfCat = catList.parallelStream().max(Comparator.comparing(Cat::getAge)).get();
System.out.println("----- max line ------");
System.err.println(maxAgeOfCat.toString());
// 11. count
long count = catList.parallelStream().count();
System.out.println("----- count line -----");
System.err.println(count);
// 12. anyMatch(Predicate<? super T> predicate)
boolean isAnyMatch = catList.parallelStream().anyMatch(cat -> cat.getCnName().contains("奶"));
System.out.println("----- anyMatch line -----");
System.err.println(isAnyMatch);
// 13. findAny
Cat findAnyOfCat = catList.parallelStream().filter(cat -> cat.getCnName().contains("奶")).findAny().get();
System.out.println("------ findAny line ------");
System.err.println(findAnyOfCat.toString());
/*
总结:很多时候anyMatch与findAny可以相互替换,使用方式类似
*/
// 14. allMatch(Predicate<? super T> predicate) 每个元素都必须匹配
boolean isAllMatch = catList.parallelStream().allMatch(cat -> Objects.equals(cat.getCnName(), "奶酪"));
System.out.println("------ allMatch line -------");
System.err.println(isAllMatch);
System.out.println();
System.out.println("------------------------------------- 分割线 ----------------------------------------------");
System.out.println("---------- the next methods are all for class Collectors --------------");
System.out.println();
// 1. Collector<T, ?, C> toCollection(Supplier<C> collectionFactory) 返回有序列表
List<Cat> toCollectionMethodList = catList.stream().limit(3).collect(toCollection(LinkedList::new));
System.out.println("------- Collectors.toCollection line ---------");
toCollectionMethodList.stream().forEach(System.err::println);
// 2. Collector<T, ?, List<T>> toList()
List<Cat> toListMethodList = catList.stream().skip(2).collect(toList());
System.out.println("------- Collectors.toList line -------");
toListMethodList.stream().forEach(System.err::println);
// 3. Collector<T, ?, Set<T>> toSet() 过滤去重列表
Set<Integer> toSetMethodSet = dupIntegerInitList().stream().collect(toSet());
System.out.println("------- Collectors.toSet line --------");
toSetMethodSet.stream().forEach(item -> {
System.err.print(item + " ");
});
// 4. Collector<CharSequence, ?, String> joining()
String cnNameJoiningStr = catList.stream().map(Cat::getCnName).collect(joining());
System.out.println();
System.out.println("------- Collectors.joining line -------");
System.err.println(cnNameJoiningStr);
// 5. Collector<CharSequence, ?, String> joining(CharSequence delimiter)
String cnNameJoiningWithDelimiterStr = catList.stream().map(Cat::getCnName).collect(Collectors.joining(" && "));
System.out.println();
System.out.println("------ Collectors.joining(CharSequence delimiter) line --------");
System.err.println(cnNameJoiningWithDelimiterStr);
// 6. Collector<CharSequence, ?, String> joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix)
String cnNameJoiningWithPrefixAndSuffixStr = catList.stream().map(Cat::getCnName).collect(joining(" && ", "pre ", " suf"));
System.out.println();
System.out.println("------ Collectors.joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix) line --------");
System.err.println(cnNameJoiningWithPrefixAndSuffixStr);
/*
7. Collector<T, ?, R> mapping(Function<? super T, ? extends U> mapper, Collector<? super U, A, R> downstream)
mapping中有一段注释非常有用,需要仔细揣摩:
The {@code mapping()} collectors are most useful when used in a multi-level reduction, such as downstream of a {@code groupingBy} or
{@code partitioningBy}. for example:
Map<City, Set<String>> lastNamesByCity = people.stream().collect(groupingBy(Person::getCity, mapping(Person::getLastName, toSet())));
*/
Map<Integer, Set<String>> mappingMethod = catList.stream().collect(groupingBy(Cat::getAge, mapping(Cat::getCnName, toSet())));
System.out.println();
System.out.println("-------- Collectors.mapping line --------");
mappingMethod.values().stream().forEach(cnNameStr -> {
System.err.print(cnNameStr + " && ");
});
// 8. Collector<T,A,RR> collectingAndThen(Collector<T,A,R> downstream, Function<R,RR> finisher)
String collectingAndThenStr = catList.parallelStream().map(x -> x.getCnName()).collect(collectingAndThen(Collectors.joining(" && ", "pre ", " suf "), k -> k + " end "));
System.out.println();
System.out.println("------ Collectors.collectingAndThen line -------");
System.err.println(collectingAndThenStr);
// 9. Collector<T, ?, Optional<T>> minBy(Comparator<? super T> comparator)
Optional<Cat> minByAgeOfCat = catList.parallelStream().collect(minBy(Comparator.comparing(Cat::getAge)));
System.out.println();
System.out.println("-------- Collectors.minBy line ---------");
System.out.println(minByAgeOfCat.get().toString());
// 10. Collector<T, ?, Optional<T>> maxBy(Comparator<? super T> comparator)
Optional<Cat> maxByAgeOfCat = catList.parallelStream().collect(maxBy(Comparator.comparing(Cat::getAge)));
System.out.println();
System.out.println("-------- Collectors.maxBy line ---------");
System.out.println(maxByAgeOfCat.get().toString());
// 11. Collector<T, ?, Integer> summingInt(ToIntFunction<? super T> mapper)
int totalAgeOfCat = catList.parallelStream().collect(summingInt(Cat::getAge));
System.out.println();
System.out.println("------- Collectors.summingInt line -------");
System.out.println(totalAgeOfCat);
// 12. Collector<T, ?, Double> averagingInt(ToIntFunction<? super T> mapper)
double averagingOfCat = catList.parallelStream().collect(averagingInt(Cat::getAge));
System.out.println();
System.out.println("------ Collector.averagingInt line -------");
System.out.println(averagingOfCat);
// 13. Collector<T, ?, Map<K, List<T>>> groupingBy(Function<? super T, ? extends K> classifier)
Map<Integer, List<Cat>> groupingByAgeOfCatMapList = catList.parallelStream().collect(groupingBy(Cat::getAge));
System.out.println();
System.out.println("------ Collector.groupingBy(one param) line -------");
System.err.println("the type of map is HashMap : " + (groupingByAgeOfCatMapList instanceof HashMap));
groupingByAgeOfCatMapList.forEach((k, v) -> {
System.err.println("type of v(list) is ArrayList : " + (v instanceof ArrayList));
v.parallelStream().forEach(System.err::println);
});
// 14. Collector<T, ?, Map<K, D>> groupingBy(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)
Map<Integer, List<Cat>> groupByAgeOfCatMapList1 = catList.parallelStream().collect(groupingBy(Cat::getAge, toCollection(LinkedList::new)));
System.out.println();
System.out.println("------ Collectors.groupingBy(two param) line -------");
System.err.println("the type of map is HashMap : " + (groupByAgeOfCatMapList1 instanceof HashMap));
groupByAgeOfCatMapList1.forEach((k, v) -> {
System.err.println("type of v(list) is LinkedList : " + (v instanceof LinkedList));
v.parallelStream().forEach(System.err::println);
});
// 15. Collector<T, ?, M> groupingBy(Function<? super T, ? extends K> classifier, Supplier<M> mapFactory, Collector<? super T, A, D> downstream)
Map<Integer, List<Cat>> groupByAgeOfCatMapList2 = catList.parallelStream().collect(groupingBy(Cat::getAge, LinkedHashMap::new, toCollection(ArrayList::new)));
System.out.println();
System.out.println("----- Collectors.groupingBy(three param) line ------");
System.err.println("the type of map is HashMap : " + (groupByAgeOfCatMapList2 instanceof HashMap));
groupByAgeOfCatMapList2.forEach((k, v) -> {
System.err.println("type of v(list) is ArrayList : " + (v instanceof ArrayList));
v.parallelStream().forEach(System.err::println);
});
// 16. Collector<T, ?, ConcurrentMap<K, List<T>>> groupingByConcurrent(Function<? super T, ? extends K> classifier)
Map<Integer, List<Cat>> groupingByAgeOfCatConcurrentMapList = catList.parallelStream().collect(groupingByConcurrent(Cat::getAge));
System.out.println();
System.out.println("----- Collectors.groupingByConcurrent(one param) line ------");
System.err.println("the type of map is ConcurrentHashMap : " + (groupingByAgeOfCatConcurrentMapList instanceof ConcurrentHashMap));
groupingByAgeOfCatConcurrentMapList.forEach((k, v) -> {
System.err.println("type of v(list) is ArrayList : " + (v instanceof ArrayList));
});
// 17. Collector<T, ?, ConcurrentMap<K, D>> groupingByConcurrent(Function<? super T, ? extends K> classifier, Collector<? super T, A, D> downstream)
Map<Integer, List<Cat>> groupingByAgeOfCatConcurrentMapList1 = catList.parallelStream().collect(groupingByConcurrent(Cat::getAge, toCollection(LinkedList::new)));
System.out.println();
System.out.println("------ Collectors.groupingByConcurrent(two param) line ------");
System.err.println("the type of map is ConcurrentHashMap : " + (groupingByAgeOfCatConcurrentMapList1 instanceof ConcurrentHashMap));
groupingByAgeOfCatConcurrentMapList1.forEach((k, v) -> {
System.err.println("type of v(list) is LinkedList : " + (v instanceof LinkedList));
});
// 18. Collector<T, ?, M> groupingByConcurrent(Function<? super T, ? extends K> classifier, Supplier<M> mapFactory, Collector<? super T, A, D> downstream)
Map<Integer, List<Cat>> groupingByAgeOfCatConcurrentMapList2 = catList.parallelStream().collect(groupingByConcurrent(Cat::getAge, ConcurrentSkipListMap::new, toCollection(LinkedList::new)));
System.out.println();
System.out.println("------ Collectors.groupingByConcurrent(three param) line ------");
System.err.println("the type of map is ConcurrentSkipListMap : " + (groupingByAgeOfCatConcurrentMapList2 instanceof ConcurrentSkipListMap));
groupingByAgeOfCatConcurrentMapList2.forEach((k, v) -> {
System.err.println("type of v(list) is LinkedList : " + (v instanceof LinkedList));
});
// 19. Collector<T, ?, Map<Boolean, List<T>>> partitioningBy(Predicate<? super T> predicate)
Map<Boolean, List<Cat>> partitioningByAgeOfCatList = catList.parallelStream().collect(partitioningBy(x -> x.getAge() > 1));
System.out.println();
System.out.println("------ Collectors.partitioningBy(one param) line ------");
System.err.println("the type of map is HashMap : " + (partitioningByAgeOfCatList instanceof HashMap));
partitioningByAgeOfCatList.forEach((k, v) -> {
System.err.println("type of v(list) is ArrayList : " + (v instanceof ArrayList));
});
// 20. Collector<T, ?, Map<Boolean, D>> partitioningBy(Predicate<? super T> predicate, Collector<? super T, A, D> downstream)
Map<Boolean, List<Cat>> partitioningByAgeOfCatList1 = catList.parallelStream().collect(partitioningBy(x -> x.getAge() < 3, toCollection(LinkedList::new)));
System.out.println();
System.out.println("------ Collectors.partitioningBy(two param) line ------");
System.err.println("the type of map is HashMap : " + (partitioningByAgeOfCatList1 instanceof HashMap));
System.err.println("the type of map is LinkedHashMap : " + (partitioningByAgeOfCatList1 instanceof LinkedHashMap));
System.err.println("the type of map is TreeMap : " + (partitioningByAgeOfCatList1 instanceof TreeMap));
System.err.println("the type of map is Hashtable : " + (partitioningByAgeOfCatList1 instanceof Hashtable));
System.err.println("the type of map is ConcurrentHashMap : " + (partitioningByAgeOfCatList1 instanceof ConcurrentHashMap));
System.err.println("the type of map is ConcurrentSkipListMap : " + (partitioningByAgeOfCatList1 instanceof ConcurrentSkipListMap));
System.err.println("the type of map is Map : " + (partitioningByAgeOfCatList1 instanceof Map));
partitioningByAgeOfCatList1.forEach((k, v) -> {
System.err.println("type of v(list) is LinkedList : " + (v instanceof LinkedList));
});
/*
总结:partitionBy返回的Map直接是一个Map接口,没有具体的实现类。且,返回的Map结构中,以true与false为key的值都有,在处理值的时候根据需求过滤。
// 21. 下面尝试下变种的一些写法: 返回值的核心都是list
*/
Map<Boolean, List<String>> partitioningByAgeOfCatList2 = catList.parallelStream().collect(partitioningBy(k -> k.getAge() < 3, mapping(Cat::getCnName, toCollection(LinkedList::new))));
System.out.println();
System.out.println("----- Collectors.partitioningBy(two param) [other way to result] line -------");
System.err.println("the type of map is Map : " + (partitioningByAgeOfCatList2 instanceof Map));
// Map<false, List<String>> && Map<true, List<String>>
partitioningByAgeOfCatList2.forEach((k, v) -> {
if (k) {
v.parallelStream().forEach(System.err::println);
}
});
// 22. Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper)
Map<Integer, String> toMapOfCatList = Arrays.asList(new Cat(1, "新来的", "new1", true)
, new Cat(2, "是我呀", "new2", false))
.parallelStream().collect(toMap(Cat::getAge, Cat::getCnName));
System.out.println();
System.out.println("------ Collectors.toMap(two param) line -------");
System.err.println("the type of map is HashMap : " + (toMapOfCatList instanceof HashMap));
toMapOfCatList.forEach((k, v) -> {
System.err.println(v);
});
// 23. Collector<T, ?, Map<K,U>> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper, BinaryOperator<U> mergeFunction)
Map<Integer, String> toMapOfCatList1 = catList.parallelStream().collect(toMap(Cat::getAge, Cat::getEnName, (e1, e2) -> e1 + e2));
System.out.println();
System.out.println("------ Collectors.toMap(three param) line -------");
System.err.println("the type of map is HashMap : " + (toMapOfCatList1 instanceof HashMap));
toMapOfCatList1.forEach((k, v) -> {
System.err.println(v);
});
/*
24. Collector<T, ?, M> toMap(Function<? super T, ? extends K> keyMapper, Function<? super T, ? extends U> valueMapper,
BinaryOperator<U> mergeFunction, Supplier<M> mapSupplier)
*/
Map<Integer, String> toMapOfCatList2 = catList.parallelStream().collect(toMap(Cat::getAge, Cat::getEnName, (e1, e2) -> e1, ConcurrentHashMap::new));
System.out.println();
System.out.println("------ Collectors.toMap(four param) line -------");
System.err.println("the type of map is ConcurrentHashMap : " + (toMapOfCatList2 instanceof ConcurrentHashMap));
toMapOfCatList2.forEach((k, v) -> {
System.err.println(v);
});
// one. list to map -->
Map<Integer, String> toMapOfCatList3 = catList.parallelStream()
.sorted(Comparator
.comparing(Cat::getAge)
.thenComparing(Cat::getEnName)
.reversed())
.collect(toMap(Cat::getAge, Cat::getEnName, (e1, e2) -> e1, ConcurrentSkipListMap::new));
System.out.println();
System.out.println("----- Collectors.toMap(four param) line [list to map, enName as value] ------");
System.err.println("the type of map is ConcurrentSkipListMap : " + (toMapOfCatList3 instanceof ConcurrentSkipListMap));
toMapOfCatList3.forEach((k, v) -> {
System.err.println(v);
});
// two. list to map --> Cat as value
Map<Integer, Cat> toMapOfCatList4 = catList.parallelStream().collect(toMap(Cat::getAge, Function.identity(), (e1, e2) -> e1, ConcurrentHashMap::new));
System.out.println();
System.out.println("------ Collectors.toMap(four param) line [list to map, Cat as value]");
System.err.println("the type of map is ConcurrentHashMap : " + (toMapOfCatList4 instanceof ConcurrentHashMap));
toMapOfCatList4.forEach((k, v) -> {
System.err.println(v);
});
// map to another map, firstDemo
Map<Integer, Integer> resultMap = new LinkedHashMap<>();
initMap().entrySet().parallelStream().sorted(Map.Entry.comparingByKey()).forEachOrdered(e -> resultMap.put(e.getKey(), e.getValue()));
// initMap().entrySet().parallelStream().sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())).forEachOrdered(e -> resultMap.put(e.getKey(), e.getValue()));
System.out.println();
System.out.println("----- map to map line [order by key] -------");
resultMap.entrySet().forEach(entry -> {
System.err.println(" ordered by key , key is : " + entry.getKey() + " , value is : " + entry.getValue());
});
// map to another map, secondDemo
/*
Map<Integer, Integer> resultMap1 = initMap().entrySet().parallelStream().sorted(Map.Entry.comparingByKey()).collect(toMap())
这个方法行不通,toMap中不知道怎么写
*/
Map<Integer, Integer> resultMap1 = new LinkedHashMap<>();
initMap().entrySet().parallelStream().sorted(Map.Entry.comparingByValue(Comparator.reverseOrder())).forEachOrdered(e -> resultMap1.put(e.getKey(), e.getValue()));
System.out.println();
System.out.println("------ map to map line [order by value] -----");
resultMap1.entrySet().stream().forEach(entry -> {
System.err.println(" ordered by value, key is : " + entry.getKey() + " , value is : " + entry.getValue());
});
}
private static Map<Integer, Integer> initMap() {
return new HashMap<Integer, Integer>() {{
put(1, 10);
put(3, 12);
put(2, 11);
put(4, 13);
}};
}
private static void readMeFirst() {
/*
1.Stream 流的常规操作可归类如下:
. intermediate(中间流 [可一个或多个])
map (mapToInt, flatMap 等)、 filter、 distinct、 sorted、 peek、 limit、 skip、 parallel、 sequential、 unordered
. terminal(终结流 [只可有一个])
forEach、 forEachOrdered、 toArray、 reduce、 collect、 min、 max、 count、 anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 iterator
. short-circuiting(短路 [可随时终止])
anyMatch、 allMatch、 noneMatch、 findFirst、 findAny、 limit
*/
}
private static List<Integer> dupIntegerInitList() {
return new ArrayList<Integer>() {{
add(1);
add(1);
add(2);
add(3);
}};
}
private static List<Cat> dupCatInitList() {
return new ArrayList<Cat>() {{
add(new Cat(1, "刘啵啵儿", "liuboboer", true));
add(new Cat(1, "刘啵啵儿", "liuboboer", true));
}};
}
private static List<Cat> initList() {
return new ArrayList<Cat>() {{
add(new Cat(2, "奶油", "cream", true));
add(new Cat(2, "奶酪", "cheese", true));
add(new Cat(3, "曾三妹", "sisterThree", false));
add(new Cat(4, "七夕", "seventh", true));
}};
}
private static List<List<Integer>> flatMapInitList() {
return new ArrayList<List<Integer>>() {{
add(Arrays.asList(1, 2, 3));
add(Arrays.asList(4, 5));
add(Arrays.asList(6, 7, 8));
}};
}
}
class Cat {
/**
* 年龄
*/
private Integer age;
/**
* 中文名称
*/
private String cnName;
/**
* 英文名称
*/
private String enName;
/**
* 是否为男性
*/
private Boolean isMale;
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getCnName() {
return cnName;
}
public void setCnName(String cnName) {
this.cnName = cnName;
}
public String getEnName() {
return enName;
}
public void setEnName(String enName) {
this.enName = enName;
}
public Boolean getMale() {
return isMale;
}
public void setMale(Boolean male) {
isMale = male;
}
public Cat() {
}
public Cat(Integer age, String cnName, String enName, Boolean isMale) {
this.age = age;
this.cnName = cnName;
this.enName = enName;
this.isMale = isMale;
}
@Override
public String toString() {
return "Cat{" +
"age=" + age +
", cnName='" + cnName + '\'' +
", enName='" + enName + '\'' +
", isMale=" + isMale +
'}';
}
}
实例数据源
public class PersonModel {
private String name;
private int age;
private String 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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public PersonModel() {
}
public PersonModel(String name, int age, String sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
@Override
public String toString() {
return "PersonModel{" +
"name='" + name + '\'' +
", age=" + age +
", sex='" + sex + '\'' +
'}';
}
}
public class Data {
private static List<PersonModel> list = null;
static {
PersonModel wu = new PersonModel("wu qi", 18, "男");
PersonModel zhang = new PersonModel("zhang san", 19, "男");
PersonModel wang = new PersonModel("wang si", 20, "女");
PersonModel zhao = new PersonModel("zhao wu", 20, "男");
PersonModel chen = new PersonModel("chen liu", 21, "男");
list = Arrays.asList(wu, zhang, wang, zhao, chen);
}
public static List<PersonModel> getData() {
return list;
}
}
Filter
1、遍历数据并检查其中的元素时使用。
2、filter接受一个函数作为参数,该函数用Lambda表达式表示。
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class Test1 {
public static void main(String[] args) {
/**
* 过滤所有的男性
*/
List<PersonModel> data = Data.getData();
// 以前的写法
List<PersonModel> temp=new ArrayList<>();
for (PersonModel person: data) {
if("男".equals(person.getSex())){
temp.add(person);
}
}
System.out.println(temp);
// 现在的写法
List<PersonModel> collect = data
.stream()
.filter(person -> "男".equals(person.getSex()))
.collect(toList());
System.out.println(collect);
}
}
根据以上的测试,查看结果temp和collect都是相同的。
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class Test2 {
public static void main(String[] args) {
/**
* 过滤所有的男性,并且年纪小于20岁
*/
List<PersonModel> data1 = Data.getData();
//以前的写法
List<PersonModel> temp1=new ArrayList<>();
for (PersonModel person: data1) {
if("男".equals(person.getSex())&&person.getAge()<20){
temp1.add(person);
}
}
System.out.println(temp1);
//现在的写法
List<PersonModel> collect1 = data1
.stream()
.filter(person -> {
if ("男".equals(person.getSex()) && person.getAge() < 20) {
return true;
}
return false;
})
.collect(toList());
System.out.println(collect1);
// 另外一种写法
List<PersonModel> collect2 = data1
.stream()
.filter(person -> ("男").equals(person.getSex()) && person.getAge() < 20)
.collect(toList());
System.out.println(collect2);
}
}
根据以上的测试,查看结果temp1和collect1、collect2都是相同的。
Map
1、map生成的是个一对一映射,for的作用
2、比较常用
3、而且很简单
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.toList;
public class Test3 {
public static void main(String[] args) {
/**
* 取出所有的用户名字
*/
List<PersonModel> data2 = Data.getData();
// 以前的写法
List<String> list=new ArrayList<>();
for (PersonModel person : data2) {
list.add(person.getName());
}
System.out.println(list);
// 现在的写法一
List<String> collect = data2
.stream()
.map(person -> person.getName())
.collect(toList());
System.out.println(collect);
// 现在的写法二
List<String> collect1 = data2
.stream()
.map(PersonModel::getName)
.collect(toList());
System.out.println(collect1);
// 现在的写法三
List<String> collect2 = data2
.stream()
.map(person -> {
System.out.println(person.getName());
return person.getName();
})
.collect(toList());
System.out.println(collect2);
}
}
经过测试,最终的结果都是一样的。
FlatMap
1、顾名思义,跟map差不多,更深层次的操作
2、但还是有区别的
3、map和flat返回值不同
4、Map 每个输入元素,都按照规则转换成为另外一个元素。
还有一些场景,是一对多映射关系的,这时需要 flatMap。
5、Map一对一
6、Flatmap一对多
7、map和flatMap的方法声明是不一样的
(1) Stream map(Function mapper);
(2) Stream flatMap(Function> mapper);
(3) map和flatMap的区别:我个人认为,flatMap的可以处理更深层次的数据,入参为多个list,结果可以返回为一个list,而map是一对一的,入参是多个list,结果返回必须是多个list。通俗的说,如果入参都是对象,那么flatMap可以操作对象里面的对象,而map只能操作第一层。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static java.util.stream.Collectors.toList;
public class Test4 {
public static void main(String[] args) {
/**
* 测试使用flatMap
*/
List<PersonModel> data3 = Data.getData();
List<String> collect = data3
.stream()
.flatMap(person -> Arrays.stream(person.getName().split(" ")))
.collect(toList());
System.out.println(collect);
// collect1返回的类型和其他不一样
List<Stream<String>> collect1 = data3
.stream()
.map(person -> Arrays.stream(person.getName().split(" ")))
.collect(toList());
System.out.println(collect1);
// 用map实现
List<String> collect2 = data3
.stream()
.map(person -> person.getName().split(" "))
.flatMap(Arrays::stream).collect(toList());
System.out.println(collect2);
//用另外一种方式实现
List<String> collect3 = data3
.stream()
.map(person -> person.getName().split(" "))
.flatMap(str -> Arrays.asList(str).stream())
.collect(toList());
System.out.println(collect3);
}
}
Reduce
1、感觉类似递归
2、数字(字符串)累加
3、个人没咋用过
public static void reduceTest(){
//累加,初始化值是 10
Integer reduce = Stream.of(1, 2, 3, 4)
.reduce(10, (count, item) ->{
System.out.println("count:"+count);
System.out.println("item:"+item);
return count + item;
} );
System.out.println(reduce);
Integer reduce1 = Stream.of(1, 2, 3, 4)
.reduce(0, (x, y) -> x + y);
System.out.println(reduce1);
String reduce2 = Stream.of("1", "2", "3")
.reduce("0", (x, y) -> (x + "," + y));
System.out.println(reduce2);
}
Collect
1、collect在流中生成列表,map,等常用的数据结构
2、toList()
3、toSet()
4、toMap()
5、自定义
/**
* toList
*/
public static void toListTest(){
List<PersonModel> data = Data.getData();
List<String> collect = data.stream()
.map(PersonModel::getName)
.collect(Collectors.toList());
}
/**
* toSet
*/
public static void toSetTest(){
List<PersonModel> data = Data.getData();
Set<String> collect = data.stream()
.map(PersonModel::getName)
.collect(Collectors.toSet());
}
/**
* toMap
*/
public static void toMapTest(){
List<PersonModel> data = Data.getData();
Map<String, Integer> collect = data.stream()
.collect(
Collectors.toMap(PersonModel::getName, PersonModel::getAge)
);
data.stream()
.collect(Collectors.toMap(per->per.getName(), value->{
return value+"1";
}));
}
/**
* 指定类型
*/
public static void toTreeSetTest(){
List<PersonModel> data = Data.getData();
TreeSet<PersonModel> collect = data.stream()
.collect(Collectors.toCollection(TreeSet::new));
System.out.println(collect);
}
/**
* 分组
*/
public static void toGroupTest(){
List<PersonModel> data = Data.getData();
Map<Boolean, List<PersonModel>> collect = data.stream()
.collect(Collectors.groupingBy(per -> "男".equals(per.getSex())));
System.out.println(collect);
}
/**
* 分隔
*/
public static void toJoiningTest(){
List<PersonModel> data = Data.getData();
String collect = data.stream()
.map(personModel -> personModel.getName())
.collect(Collectors.joining(",", "{", "}"));
System.out.println(collect);
}
/**
* 自定义
*/
public static void reduce(){
List<String> collect = Stream.of("1", "2", "3").collect(
Collectors.reducing(new ArrayList<String>(), x -> Arrays.asList(x), (y, z) -> {
y.addAll(z);
return y;
}));
System.out.println(collect);
}
Optional
1、Optional 是为核心类库新设计的一个数据类型,用来替换 null 值。
2、人们对原有的 null 值有很多抱怨,甚至连发明这一概念的Tony Hoare也是如此,他曾说这是自己的一个“价值连城的错误”
3、用处很广,不光在lambda中,哪都能用
4、Optional.of(T),T为非空,否则初始化报错
5、Optional.ofNullable(T),T为任意,可以为空
6、isPresent(),相当于 !=null
7、ifPresent(T), T可以是一段lambda表达式 ,或者其他代码,非空则执行
public static void main(String[] args) {
PersonModel personModel=new PersonModel();
//对象为空则打出 -
Optional<Object> o = Optional.of(personModel);
System.out.println(o.isPresent()?o.get():"-");
//名称为空则打出 -
Optional<String> name = Optional.ofNullable(personModel.getName());
System.out.println(name.isPresent()?name.get():"-");
//如果不为空,则打出xxx
Optional.ofNullable("test").ifPresent(na->{
System.out.println(na+"ifPresent");
});
//如果空,则返回指定字符串
System.out.println(Optional.ofNullable(null).orElse("-"));
System.out.println(Optional.ofNullable("1").orElse("-"));
//如果空,则返回 指定方法,或者代码
System.out.println(Optional.ofNullable(null).orElseGet(()->{
return "hahah";
}));
System.out.println(Optional.ofNullable("1").orElseGet(()->{
return "hahah";
}));
//如果空,则可以抛出异常
System.out.println(Optional.ofNullable("1").orElseThrow(()->{
throw new RuntimeException("ss");
}));
// Objects.requireNonNull(null,"is null");
//利用 Optional 进行多级判断
EarthModel earthModel1 = new EarthModel();
//old
if (earthModel1!=null){
if (earthModel1.getTea()!=null){
//...
}
}
//new
Optional.ofNullable(earthModel1)
.map(EarthModel::getTea)
.map(TeaModel::getType)
.isPresent();
// Optional<EarthModel> earthModel = Optional.ofNullable(new EarthModel());
// Optional<List<PersonModel>> personModels = earthModel.map(EarthModel::getPersonModels);
// Optional<Stream<String>> stringStream = personModels.map(per -> per.stream().map(PersonModel::getName));
//判断对象中的list
Optional.ofNullable(new EarthModel())
.map(EarthModel::getPersonModels)
.map(pers->pers
.stream()
.map(PersonModel::getName)
.collect(toList()))
.ifPresent(per-> System.out.println(per));
List<PersonModel> models=Data.getData();
Optional.ofNullable(models)
.map(per -> per
.stream()
.map(PersonModel::getName)
.collect(toList()))
.ifPresent(per-> System.out.println(per));
}
并发
1、stream替换成parallelStream或 parallel
2、输入流的大小并不是决定并行化是否会带来速度提升的唯一因素,性能还会受到编写代码的方式和核的数量的影响
3、影响性能的五要素是:数据大小、源数据结构、值是否装箱、可用的CPU核数量,以及处理每个元素所花的时间
//根据数字的大小,有不同的结果
private static int size=10000000;
public static void main(String[] args) {
System.out.println("-----------List-----------");
testList();
System.out.println("-----------Set-----------");
testSet();
}
/**
* 测试list
*/
public static void testList(){
List<Integer> list = new ArrayList<>(size);
for (Integer i = 0; i < size; i++) {
list.add(new Integer(i));
}
List<Integer> temp1 = new ArrayList<>(size);
//老的
long start=System.currentTimeMillis();
for (Integer i: list) {
temp1.add(i);
}
System.out.println(+System.currentTimeMillis()-start);
//同步
long start1=System.currentTimeMillis();
list.stream().collect(Collectors.toList());
System.out.println(System.currentTimeMillis()-start1);
//并发
long start2=System.currentTimeMillis();
list.parallelStream().collect(Collectors.toList());
System.out.println(System.currentTimeMillis()-start2);
}
/**
* 测试set
*/
public static void testSet(){
List<Integer> list = new ArrayList<>(size);
for (Integer i = 0; i < size; i++) {
list.add(new Integer(i));
}
Set<Integer> temp1 = new HashSet<>(size);
//老的
long start=System.currentTimeMillis();
for (Integer i: list) {
temp1.add(i);
}
System.out.println(+System.currentTimeMillis()-start);
//同步
long start1=System.currentTimeMillis();
list.stream().collect(Collectors.toSet());
System.out.println(System.currentTimeMillis()-start1);
//并发
long start2=System.currentTimeMillis();
list.parallelStream().collect(Collectors.toSet());
System.out.println(System.currentTimeMillis()-start2);
}
调试
1、list.map.fiter.map.xx 为链式调用,最终调用collect(xx)返回结果
2、分惰性求值和及早求值
3、判断一个操作是惰性求值还是及早求值很简单:只需看它的返回值。如果返回值是 Stream,那么是惰性求值;如果返回值是另一个值或为空,那么就是及早求值。使用这些操作的理想方式就是形成一个惰性求值的链,最后用一个及早求值的操作返回想要的结果。
4、通过peek可以查看每个值,同时能继续操作流
private static void peekTest() {
List<PersonModel> data = Data.getData();
//peek打印出遍历的每个per
data.stream().map(per->per.getName()).peek(p->{
System.out.println(p);
}).collect(toList());
}