0
点赞
收藏
分享

微信扫一扫

java8中Stream的一些使用例子总结

Stream API

例子

如果有一个需求,需要对数据库查询到的菜肴进行一个处理:

  • 筛选出卡路里小于400的菜肴
  • 对筛选出的菜肴进行一个排序
  • 获取排序后菜肴的名字
    菜肴:Dish.java
public class Dish {
private String name;
private boolean vegetarian;
private int calories;
private Type type;

// getter and setter
}

以往的方式

private List<String> beforeJava7(List<Dish> dishList) {
List<Dish> lowCaloricDishes = new ArrayList<>();

//1.筛选出卡路里小于400的菜肴
for (Dish dish : dishList) {
if (dish.getCalories() < 400) {
lowCaloricDishes.add(dish);
}
}

//2.对筛选出的菜肴进行排序
Collections.sort(lowCaloricDishes, new Comparator<Dish>() {
@Override
public int compare(Dish o1, Dish o2) {
return Integer.compare(o1.getCalories(), o2.getCalories());
}
});

//3.获取排序后菜肴的名字
List<String> lowCaloricDishesName = new ArrayList<>();
for (Dish d : lowCaloricDishes) {
lowCaloricDishesName.add(d.getName());
}

return lowCaloricDishesName;
}

java8

private List<String> afterJava8(List<Dish> dishList) {
return dishList.stream()
.filter(d -> d.getCalories() < 400) //筛选出卡路里小于400的菜肴
.sorted(comparing(Dish::getCalories)) //根据卡路里进行排序
.map(Dish::getName) //提取菜肴名称
.collect(Collectors.toList()); //转换为List
}

突然加新需求

· 对数据库查询到的菜肴根据菜肴种类进行分类,返回一个​​Map>​​的结果

以往的方式

private static Map<Type, List<Dish>> beforeJdk8(List<Dish> dishList) {
Map<Type, List<Dish>> result = new HashMap<>();

for (Dish dish : dishList) {
//不存在则初始化
if (result.get(dish.getType())==null) {
List<Dish> dishes = new ArrayList<>();
dishes.add(dish);
result.put(dish.getType(), dishes);
} else {
//存在则追加
result.get(dish.getType()).add(dish);
}
}

return result;
}

java8

private static Map<Type, List<Dish>> afterJdk8(List<Dish> dishList) {
return dishList.stream().collect(groupingBy(Dish::getType));
}

如何生成流

1.通过集合生成

List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream();

2.通过数组生成

int[] intArr = new int[]{1, 2, 3, 4, 5};
IntStream stream = Arrays.stream(intArr);

通过​​Arrays.stream​​​方法生成流,并且该方法生成的流是数值流【即​​IntStream​​​】而不是​​Stream​​​。补充一点使用数值流可以避免计算过程中拆箱装箱,提高性能。​​Stream API​​​提供了​​mapToInt​​​、​​mapToDouble​​​、​​mapToLong​​​三种方式将对象流【即​​Stream​​​】转换成对应的数值流,同时提供了​​boxed​​方法将数值流转换为对象流

3.通过值生成

Stream<Integer> stream = Stream.of(1, 2, 3, 4, 5);

通过​​Stream​​​的​​of​​​方法生成流,通过​​Stream​​​的​​empty​​方法可以生成一个空流

4.通过文件生成

Stream<String> lines = Files.lines(Paths.get("data.txt"), Charset.defaultCharset())

通过​​Files.line​​方法得到一个流,并且得到的每个流是给定文件中的一行

5.通过函数生成

提供了​​iterate​​​和​​generate​​两个静态方法从函数中生成流

Stream<Integer> stream = Stream.iterate(0, n -> n + 2).limit(5);

​iterate​​​方法接受两个参数,第一个为初始化值,第二个为进行的函数操作,因为​​iterator​​​生成的流为无限流,通过​​limit​​方法对流进行了截断,只生成5个偶数

Stream<Double> stream = Stream.generate(Math::random).limit(5);

​generate​​​方法接受一个参数,方法参数类型为​​Supplier​​​,由它为流提供值。​​generate​​​生成的流也是无限流,因此通过​​limit​​对流进行了截断

流的操作类型

1.中间操作

一个流可以后面跟随零个或多个中间操作。其目的主要是打开流,做出某种程度的数据映射/过滤,然后返回一个新的流,交给下一个操作使用。这类操作都是惰性化的,仅仅调用到这类方法,并没有真正开始流的遍历,真正的遍历需等到终端操作时

1.1 filter筛选

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().filter(i -> i > 3);

通过使用​​filter​​​方法进行条件筛选,​​filter​​的方法参数为一个条件

实例中使用

List<Integer> giftIds = exchangeCommodities.stream()
.filter(e -> e.getType() == 2) /*只取类型为2的 其它排除掉*/
.map(LuckExchangeCommodity::getRelationId)
.collect(Collectors.toList());

1.2 distinct 去掉重复元素

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().distinct();

通过​​distinct​​方法快速去除重复的元素

1.3 limit 返回指定流个数

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().limit(3);

通过​​limit​​​方法指定返回流的个数,​​limit​​​的参数值必须​​>=0​​,否则将会抛出异常

1.4 skip 跳过流中的元素

List<Integer> integerList = Arrays.asList(1, 1, 2, 3, 4, 5);
Stream<Integer> stream = integerList.stream().skip(2);

通过​​skip​​​方法跳过流中的元素,上述例子跳过前两个元素,所以打印结果为​​2,3,4,5​​​,​​skip​​​的参数值必须​​>=0​​,否则将会抛出异常

1.5 map 流映射

List<String> stringList = Arrays.asList("Java 8", "Lambdas",  "In", "Action");
Stream<Integer> stream = stringList.stream().map(String::length);

所谓流映射就是将接受的元素映射成另外一个元素

通过​​map​​​方法可以完成映射,该例子完成中​​String \-> Integer​​​的映射,之前上面的例子通过​​map​​​方法完成了​​Dish->String​​的映射

1.6 flatMap 流转换

List<String> wordList = Arrays.asList("Hello", "World");
List<String> strList = wordList.stream()
.map(w -> w.split(" "))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());

将一个流中的每个值都转换为另一个流

​map(w \-> w.split(" "))​​​的返回值为​​Stream<String[]>​​​,我们想获取​​Stream<String[]>​​​,可以通过​​flatMap​​​方法完成​​Stream<String[]> \->Stream<String>​​的转换

1.7 元素匹配相关

提供了三种匹配方式

1.7.1 allMatch 匹配所有
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().allMatch(i -> i > 3)) {
System.out.println("值都大于3");
}
1.7.2 anyMatch 匹配其中的一个
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().anyMatch(i -> i > 3)) {
System.out.println("存在大于3的值");
}

等同于

for (Integer i : integerList) {
if (i > 3) {
System.out.println("存在大于3的值");
break;
}
}

存在大于3的值则打印,​​java8​​​中通过​​anyMatch​​方法实现这个功能

1.7.3 noneMatch 全部不匹配
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
if (integerList.stream().noneMatch(i -> i > 3)) {
System.out.println("值都小于3");
}

2.终端操作

一个流有且只能有一个终端操作,当这个操作执行后,流就被关闭了,无法再被操作,因此一个流只能被遍历一次,若想在遍历需要通过源数据在生成流。终端操作的执行,才会真正开始流的遍历

2.1 统计元素个数

有两种方法

2.1.1 通过count
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().count();

通过使用​​count​​方法统计出流中元素个数

2.1.2 通过counting
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Long result = integerList.stream().collect(counting());

统计元素个数的方法在与​​collect​​联合使用的时候特别有用

2.2 查找

提供了两种查找方式

2.2.1 findFirst 查找第一个
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> result = integerList.stream().filter(i -> i > 3).findFirst();

通过​​findFirst​​方法查找到第一个大于三的元素并打印

2.2.2 findAny 随机查找一个
List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Optional<Integer> result = integerList.stream().filter(i -> i > 3).findAny();

通过​​findAny​​​方法查找到其中一个大于三的元素并打印,因为内部进行优化的原因,当找到第一个满足大于三的元素时就结束,该方法结果和​​findFirst​​​方法结果一样。提供​​findAny​​​方法是为了更好的利用并行流,​​findFirst​​方法在并行上限制更多【本篇文章将不介绍并行流】

2.3 元素组合 reduce

2.3.1 求和
int sum = integerList.stream().reduce(0, (a, b) -> (a + b));

方法引用简写

int sum = integerList.stream().reduce(0, Integer::sum);
//或者
int sum = menu.stream().mapToInt(Dish::getCalories).sum();

​reduce​​​接受两个参数,一个初始值这里是​​0​​​,一个​​BinaryOperator accumulator​​​ 来将两个元素结合起来产生一个新值, 另外​​reduce​​方法还有一个没有初始化值的重载方法

通过 summingInt

int sum = menu.stream().collect(summingInt(Dish::getCalories));

如果数据类型为​​double​​​、​​long​​​,则通过​​summingDouble​​​、​​summingLong​​方法进行求和

通过sum

int sum = menu.stream().mapToInt(Dish::getCalories).sum();
2.3.2 最大值 最小值
Optional<Integer> min = menu.stream().map(Dish::getCalories).min(Integer::compareTo);
Optional<Integer> max = menu.stream().map(Dish::getCalories).max(Integer::compareTo);

也可以

OptionalInt min = menu.stream().mapToInt(Dish::getCalories).min();
OptionalInt max = menu.stream().mapToInt(Dish::getCalories).max();

​min​​​获取流中最小值,​​max​​​获取流中最大值,方法参数为​​Comparator comparator​

还可以 通过minBy/maxBy获取最小最大值

Optional<Integer> min = menu.stream().map(Dish::getCalories).collect(minBy(Integer::compareTo));
Optional<Integer> max = menu.stream().map(Dish::getCalories).collect(maxBy(Integer::compareTo));

​minBy​​​获取流中最小值,​​maxBy​​​获取流中最大值,方法参数为​​Comparator comparator​

还可以 通过reduce获取最小最大值

Optional<Integer> min = menu.stream().map(Dish::getCalories).reduce(Integer::min);
Optional<Integer> max = menu.stream().map(Dish::getCalories).reduce(Integer::max);

在上面求和、求最大值、最小值的时候,对于相同操作有不同的方法可以选择执行。可以选择​​collect​​​、​​reduce​​​、​​min/max/sum​​​方法,推荐使用​​min​​​、​​max​​​、​​sum​​​方法。因为它最简洁易读,同时通过​​mapToInt​​将对象流转换为数值流,避免了装箱和拆箱操作

2.3.3 求平均值

通过averagingInt求平均值

double average = menu.stream().collect(averagingInt(Dish::getCalories));

如果数据类型为​​double​​​、​​long​​​,则通过​​averagingDouble​​​、​​averagingLong​​方法进行求平均

2.3.4 一劳永逸法 summarizingInt

同时求总和,平均值,最大值,最小值

IntSummaryStatistics intSummaryStatistics = menu.stream().collect(summarizingInt(Dish::getCalories));
double average = intSummaryStatistics.getAverage(); //获取平均值
int min = intSummaryStatistics.getMin(); //获取最小值
int max = intSummaryStatistics.getMax(); //获取最大值
long sum = intSummaryStatistics.getSum(); //获取总和

如果数据类型为​​double​​​、​​long​​​,则通过​​summarizingDouble​​​、​​summarizingLong​​方法

2.4 foreach 集合遍历

List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
integerList.stream().forEach(System.out::println);

2.5 返回集合

List<String> strings = menu.stream().map(Dish::getName).collect(toList());
Set<String> sets = menu.stream().map(Dish::getName).collect(toSet());

2.6 通过 joining 拼接元素

String result = menu.stream().map(Dish::getName).collect(Collectors.joining(", "));

默认如果不通过​​map​​​方法进行映射处理拼接的​​toString​​方法返回的字符串,joining的方法参数为元素的分界符,如果不指定生成的字符串将是一串的,可读性不强

2.7 通过 groupingBy 进行分组

Map<Type, List<Dish>> result = dishList.stream().collect(groupingBy(Dish::getType));

在​​collect​​​方法中传入​​groupingBy​​​进行分组,其中​​groupingBy​​​的方法参数为分类函数。还可以通过嵌套使用​​groupingBy​​进行多级分类

2.8 通过 partitioningBy 进行分区

分区是特殊的分组,它分类依据是true和false,所以返回的结果最多可以分为两组

Map<Boolean, List<Dish>> result = menu.stream().collect(partitioningBy(Dish :: isVegetarian))

等同于

Map<Boolean, List<Dish>> result = menu.stream().collect(groupingBy(Dish :: isVegetarian))

换个明显一点的例子

List<Integer> integerList = Arrays.asList(1, 2, 3, 4, 5);
Map<Boolean, List<Integer>> result = integerList.stream().collect(partitioningBy(i -> i < 3));

返回值的键仍然是布尔类型,但是它的分类是根据范围进行分类的,分区比较适合处理根据范围进行分类

实例中使用

Map<Integer, List<LuckExchangeCommodity>> exchangeMap = 
exchangeCommodities.stream()
.collect(
Collectors.groupingBy(
LuckExchangeCommodity::getGameId /*按照什么来分组*/
,LinkedHashMap::new /*是否有序 LinkedHashMap 为有序 默认为无序*/
,Collectors.toList() /*最后置换成什么 一般为这个*/
));

2.9 排序 sort

正序 例子

giftList.sort(Comparator.comparing(GetGiftExchangeVo::getWeight));

oneTasks.stream().sorted(Comparator.comparing(LuckTaskVo::getNum)).collect(Collectors.toList())

倒叙 例子

giftList.sort(Comparator.comparing(GetGiftExchangeVo::getWeight).reversed());

oneTasks.stream().sorted(Comparator.comparing(LuckTaskVo::getNum).reversed()).collect(Collectors.toList())

2.10 转Map

Map<Integer, String> goodsTypeMap = goodsTypeDao.selectAll()
.stream()
.collect(Collectors.toMap(GoodsType::getId, GoodsType::getName));
//对象问题
Map<Integer, String> goodsTypeMap = goodsTypeDao.selectAll()
.stream()
.collect(Collectors.toMap(GoodsType::getId, goodType -> goodType));

举报

相关推荐

0 条评论