java stream min max,Java8中Stream的使用

Stream(流)是一个来自数据源的元素队列并支持聚合操作

元素是特定类型的对象,形成一个队列。 - Java中的Stream并不会存储元素,而是按需计算。

数据源,流的来源。 可以是集合,数组,I/O channel, 产生器generator 等。

聚合操作,类似SQL语句一样的操作, 比如filter, map, reduce, find, match, sorted等。

和以前的Collection操作不同, Stream操作还有两个基础的特征:

Pipelining: 中间操作都会返回流对象本身。 这样多个操作可以串联成一个管道, 如同流式风格(fluent style)。 这样做可以对操作进行优化, 比如延迟执行(laziness)和短路( short-circuiting)。

内部迭代: 以前对集合遍历都是通过Iterator或者For-Each的方式, 显式的在集合外部进行迭代, 这叫做外部迭代。 Stream提供了内部迭代的方式, 通过访问者模式(Visitor)实现。

Stream操作的三个步骤

创建 Stream

集合接口有两个方法来生成流:

stream() − 为集合创建串行流。

parallelStream() − 为集合创建并行流。

中间操作

一个中间操作链,对数据源的数据进行处理。比如fifter、distinct、limit、skip、map、sorted、

终止操作

一旦执行终止操作,就执行中间操作链,并产生结果。之后,不会再被使用。

比如:match、findFirst、count、max、min、forEach、reduce、collect

创建 Stream

一般我们使用的场景是对列表或数组操作。通过Collection的方法stream()和parallelStream()获取。

List list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);

list.stream().forEach(System.out::println);

list.parallelStream().forEach(System.out::println);

中间操作

fifter(Predicate super T> predicate)

根据过滤条件,保留符合条件的元素

List list = Lists.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9, 9);

list.stream().filter(item -> item > 5).forEach(System.out::println);

distinct ()

去重

list.stream().filter(item -> item > 5).distinct().forEach(System.out::println);

limit(long maxSize)

返回前maxSize个元素

list.stream().filter(item -> item > 5).limit(2).forEach(System.out::println);

skip(long n)

调过前n个

list.stream().filter(item -> item > 5).skip(2).forEach(System.out::println);

sorted()/sorted(Comparator super T> comparator)

// 自然排序

list.stream().sorted().forEach(System.out::println);

// 根据比较器顺序排序

list.stream().sorted((a1, a2) -> a2.compareTo(a1)).forEach(System.out::println);

map/flatMap

map(Function super T, ? extends R> mapper)

mapToInt(ToIntFunction super T> mapper)

mapToDouble(ToDoubleFunction super T> mapper)

mapToLong(ToLongFunction super T> mapper)

flatMap(Function super T, ? extends Stream extends R>> mapper)

flatMapToInt(Function super T, ? extends IntStream> mapper)

flatMapToLong(Function super T, ? extends LongStream> mapper)

flatMapToDouble(Function super T, ? extends DoubleStream> mapper)

map() 接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素

flatMap()接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流

创建一个对象product

public class Product {

private Long id;

private Integer num;

private Double price;

private String name;

public Product() {}

public Product(Long id, Integer num, Double price, String name) {

this.id = id;

this.num = num;

this.price = price;

this.name = name;

}

// get/set省略

}

Product prod1 = new Product(1L, 1, new Double(15.5), "面包");

Product prod2 = new Product(2L, 2, new Double(20), "饼干");

Product prod3 = new Product(3L, 3, new Double(30), "月饼");

List prodList = Lists.newArrayList(prod1, prod2, prod3);

List nameList = prodList.stream().map(item -> item.getName()).collect(Collectors.toList());

System.out.println(nameList); // [面包, 饼干, 月饼]

Long count = prodList.stream().mapToInt(item -> item.getNum()).count();

System.out.println(count); // 3

Long min = prodList.stream().mapToLong(item -> item.getId()).min().getAsLong();

System.out.println(min); // 1

prodList.stream().mapToDouble(item -> item.getPrice()).forEach(System.out::println);

// 15.5 20.0 30.0

List strList = prodList.stream().flatMap(item -> Arrays.stream(item.getName().split(""))).collect(Collectors.toList());

System.out.println(strList.toString());

// [面, 包, 饼, 干, 月, 饼]

终止操作

终止操作会从流的流水线生成结果。

anyMatch(Predicate super T> predicate);

检查是否有至少一个能够满足条件

Boolean anyMatch = prodList.stream().anyMatch(item -> "面包".equals(item.getName()));

System.out.println("anyMatch="+anyMatch);

allMatch(Predicate super T> predicate)

检查是否所有满足条件

Boolean allMatch = prodList.stream().allMatch(item -> "面包".equals(item.getName()));

System.out.println("allMatch="+allMatch);

noneMatch

Boolean noneMatch = prodList.stream().noneMatch(item -> "面包".equals(item.getName()));

System.out.println("noneMatch="+noneMatch);

findFirst

返回第一个

findAny

返回任意一个

System.out.println(prodList.stream().filter(item -> item.getNum() < 3).findFirst().get().getId());

System.out.println(prodList.stream().filter(item -> item.getNum() < 3).findAny().get().getId());

count()总数/min最小数/max最大数

Long count = prodList.stream().count();

Integer num = prodList.stream().min((a1, a2) -> a1.getNum().compareTo(a2.getNum())).get().getNum();

Double price = prodList.stream().max((a1, a2) -> a1.getPrice().compareTo(a2.getPrice())).get().getPrice();

System.out.println(count);

System.out.println(num);

System.out.println(price);

forEach

内部迭代

reduce

T reduce(T identity, BinaryOperator accumulator)

可以将流中元素反复结合起来,得到一个值,返回 T

Optional reduce(BinaryOperator accumulator);

将流中元素反复结合起来,得到一个值, 返回 Optional

List list = Lists.newArrayList(1, 3, 2, 4, 5, 6, 7, 8, 9);

Integer reduce = list.stream().reduce(0, (x, y) -> x+y);

System.out.println(reduce);

// 有可能为null

List prodList = Lists.newArrayList();

Optional reduceOpt = prodList.stream().map(Product::getNum).reduce(Integer::sum);

System.out.println(reduceOpt.isPresent());

collect

将流转化为其他形式,常用的List,Set、Map、Collection

// 转为list

List nameList = prodList.stream().map(item -> item.getName()).collect(Collectors.toList());

// 转为Set

Set nameSet = prodList.stream().map(item -> item.getName()).collect(Collectors.toSet());

// 转为Map

Map idMap = prodList.stream().collect(Collectors.toMap(Product::getId,Functions.identity()));

// 转为LinkedList

prodList.stream().map(item -> item.getName()).collect(Collectors.toCollection(LinkedList::new));

//统计总数

Long count = prodList.stream().collect(Collectors.counting());

// 分组

Map> listMap = prodList.stream().collect(Collectors.groupingBy(Product::getId));

// 拼接

String nameJoin = prodList.stream().map(Product::getName).collect(Collectors.joining());

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值