@Slf4j
public class StreamTest {
public static void main(String[] args) {
List<Persion> list = new ArrayList<>();
testData(list);
/**
* filter(T -> boolean)
* 保留 boolean 为 true 的元素
*/
list = list.stream()
.filter(Persion -> Persion.getAge() == 20)
.collect(toList());
log.info("filter(T -> boolean):{}", list);
/**
* distinct()
* 去除重复元素,这个方法是通过类的 equals 方法来判断两个元素是否相等的
*/
testData(list);
list = list.stream().distinct().collect(toList());
log.info("distinct():{}", list);
/**
* sorted() / sorted((T, T) -> int)
* 如果流中的元素的类实现了 Comparable 接口,即有自己的排序规则,那么可以直接调用 sorted() 方法对元素进行排序,如 Stream<Integer>
* 反之, 需要调用 sorted((T, T) -> int) 实现 Comparator 接口
*/
testData(list);
list = list.stream()
.sorted((p1, p2) -> p1.getAge() - p2.getAge())
.collect(toList());
log.info("sorted() / sorted((T, T) -> int):{}", list);
list = list.stream()
.sorted(Comparator.comparingInt(Persion::getAge))
.collect(toList());
log.info("sorted() / sorted((T, T) -> int):{}", list);
/**
* limit(long n)
* 返回前 n 个元素
*/
testData(list);
list = list.stream()
.limit(2)
.collect(toList());
log.info("limit(long n):{}", list);
/**
* skip(long n)
* 去除前 n 个元素
*/
testData(list);
list = list.stream()
.skip(2)
.collect(toList());
log.info("skip(long n):{}", list);
/**
* map(T -> R)
* 将流中的每一个元素 T 映射为 R(类似类型转换)
*/
testData(list);
List<String> newList = list.stream().map(Persion::getName).collect(toList());
log.info("map(T -> R):{}", newList);
/**
* flatMap(T -> Stream<R>)
* 将流中的每一个元素 T 映射为一个流,再把每一个流连接成为一个流
*/
List<String> flatMapList = new ArrayList<>();
flatMapList.add("aaa bbb ccc");
flatMapList.add("ddd eee fff");
flatMapList.add("ggg hhh iii");
flatMapList = flatMapList.stream().map(s -> s.split(" ")).flatMap(Arrays::stream).collect(toList());
log.info("flatMapList:{}", flatMapList);
/**
* anyMatch(T -> boolean)
* 流中是否有一个元素匹配给定的 T -> boolean 条件
*/
testData(list);
boolean anyMatchBool = list.stream().anyMatch(Persion -> Persion.getAge() == 20);
log.info("anyMatch(T -> boolean):{}", anyMatchBool);
/**
* allMatch(T -> boolean)
* 流中是否所有元素都匹配给定的 T -> boolean 条件
*/
testData(list);
boolean allMatchBool = list.stream().allMatch(Persion -> Persion.getAge() == 20);
log.info("allMatch(T -> boolean):{}", allMatchBool);
/**
* noneMatch(T -> boolean)
* 流中是否没有元素匹配给定的 T -> boolean 条件
*/
testData(list);
boolean noneMatchBool = list.stream().noneMatch(Persion -> Persion.getAge() == 20);
log.info("noneMatch(T -> boolean):{}", noneMatchBool);
/**
* findAny() 和 findFirst()
* findAny():找到其中一个元素 (使用 stream() 时找到的是第一个元素;使用 parallelStream() 并行时找到的是其中一个元素)
* findFirst():找到第一个元素
* 值得注意的是,这两个方法返回的是一个 Optional<T> 对象,它是一个容器类,能代表一个值存在或不存在
*/
testData(list);
Optional<Persion> findAnyPersion = list.stream().findAny();
log.info("findAnyPersion:{}", findAnyPersion);
Optional<Persion> findFirstPersion = list.stream().findFirst();
log.info("findFirstPersion:{}", findFirstPersion);
/**
* reduce((T, T) -> T) 和 reduce(T, (T, T) -> T)
* 用于组合流中的元素,如求和,求积,求最大值等
* 其中,reduce 第一个参数 0 代表起始值为 0,lambda (a, b) -> a + b 即将两值相加产生一个新值
*/
testData(list);
int reduceSum = list.stream().map(Persion::getAge).reduce(0, (a, b) -> a + b);
log.info("reduce(T, (T, T) -> T):{}", reduceSum);
reduceSum = list.stream().map(Persion::getAge).reduce(0, Integer::sum);
log.info("reduce((T, T) -> T):{}", reduceSum);
/**
* count()
* 返回流中元素个数,结果为 long 类型
*/
testData(list);
long count = list.stream().count();
log.info("count:{}", count);
/**
* forEach()
*/
testData(list);
list.stream().forEach(Persion -> log.info("forEach:{}", Persion));
/**
* Arrays.stream(T[ ])
* 数组创建流
*/
int[] intTmp = {1, 2, 3, 4};
Arrays.stream(intTmp, 1, 3).forEach(tmp -> log.info("tmp:{}", tmp));
/**
* toMap
* 收集
*/
list.clear();
list.add(new Persion("mike", 25));
list.add(new Persion("jack", 20));
list.add(new Persion("tom", 30));
Map<Integer, Persion> map = list.stream().collect(toMap(Persion::getAge, p -> p));
log.info("toMap:{}", map);
/**
* counting
* 用于计算总和
*/
testData(list);
long counting = list.stream().collect(counting());
log.info("counting:{}", counting);
counting = list.stream().count();
log.info("counting -> count:{}", counting);
/**
* summingInt ,summingLong ,summingDouble
* 计算总和
*/
testData(list);
int summingInt = list.stream().collect(summingInt(Persion::getAge));
log.info("summingInt:{}", summingInt);
summingInt = list.stream().mapToInt(Persion::getAge).sum();
log.info("mapToInt:{}", summingInt);
summingInt = list.stream().map(Persion::getAge).reduce(Integer::sum).get();
log.info("map -> reduce:{}", summingInt);
/**
* averagingInt,averagingLong,averagingDouble
* 求平均数
*/
testData(list);
Double average = list.stream().collect(averagingInt(Persion::getAge));
log.info("averagingInt:{}", average);
/**
* summarizingInt,summarizingLong,summarizingDouble
* summarizingInt 会返回 IntSummaryStatistics 类型
* IntSummaryStatistics 包含了计算出来的平均值,总数,总和,最值
*/
IntSummaryStatistics intSummaryStatistics = list.stream().collect(summarizingInt(Persion::getAge));
long intSummaryStatisticsCount = intSummaryStatistics.getCount();
log.info("intSummaryStatisticsCount:{}", intSummaryStatisticsCount);
double intSummaryStatisticsAverage = intSummaryStatistics.getAverage();
log.info("intSummaryStatisticsAverage:{}", intSummaryStatisticsAverage);
int intSummaryStatisticsMax = intSummaryStatistics.getMax();
log.info("intSummaryStatisticsMax:{}", intSummaryStatisticsMax);
int intSummaryStatisticsMin = intSummaryStatistics.getMin();
log.info("intSummaryStatisticsMin:{}", intSummaryStatisticsMin);
long intSummaryStatisticsSum = intSummaryStatistics.getSum();
log.info("intSummaryStatisticsSum:{}", intSummaryStatisticsSum);
/**
* joining
* 连接字符串
*/
testData(list);
String join = list.stream().map(Persion::getName).collect(joining());
log.info("join:{}", join);
String joining = list.stream().map(Persion::getName).collect(joining(","));
log.info("joining:{}", joining);
/**
* joining
* 重载方法
*/
String joiningOverload = list.stream().map(Persion::getName).collect(joining(" and ", "Today ", " play games."));
log.info("joining Overload:{}", joiningOverload);
/**
* groupingBy
* 将数据分组,最终返回一个 Map 类型
*/
testData(list);
Map<Integer, List<Persion>> groupingByMap = list.stream().collect(groupingBy(Persion::getAge));
log.info("groupingByMap:{}", groupingByMap);
Map<Integer, Map<String, List<Persion>>> groupingByMoreMap = list.stream().collect(groupingBy(Persion::getAge, groupingBy(Persion::getName)));
log.info("groupingByMoreMap:{}", groupingByMoreMap);
Map<Integer, Integer> groupingByMapSummingInt = list.stream().collect(groupingBy(Persion::getAge, summingInt(Persion::getAge)));
log.info("groupingByMapSummingInt:{}", groupingByMapSummingInt);
/**
* partitioningBy
* 分区
*/
testData(list);
Map<Boolean, List<Persion>> partitioningByMap = list.stream().collect(partitioningBy(p -> p.getAge() <= 20));
log.info("partitioningByMap:{}", partitioningByMap);
}
/***
* 重新赋值测试数据
* @param list
*/
public static void testData(List<Persion> list) {
list.clear();
list.add(new Persion("mike", 25));
list.add(new Persion("jack", 20));
list.add(new Persion("jack", 20));
list.add(new Persion("tom", 30));
}
}
@Data
@AllArgsConstructor
class Persion implements Serializable {
private static final long serialVersionUID = -864087087674466387L;
private String name;
private Integer age;
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Persion)) {
return false;
}
final Persion Persion = (Persion) obj;
return this.age == Persion.age;
}
public int hashCode() {
return Objects.hashCode(age);
}
}
网友评论