文章目录
Stream流
提供更好操作的集合库
- Guava
- Apach Commons Collections
- lambdaj - Mario Fusco
初始操作
stream stream流
List<String> threeHighCaloricDishNames =
Dish.menu
//生成stream
.stream()
//筛选
.filter(d->d.getCalories()>300)
//提取
.map(Dish::getName)
//截断
.limit(3)
//生成
.collect(Collectors.toList());
System.out.println(threeHighCaloricDishNames);
parallelStream 多核流
List<String> threeHighCaloricDishNames =
Dish.menu
//多内核使用的Stream
.parallelStream()
//筛选
.filter(d->d.getCalories()>300)
//提取
.map(Dish::getName)
//截断
.limit(3)
//生成
.collect(Collectors.toList());
System.out.println(threeHighCaloricDishNames);
Map进行流操作
Map<Integer,Integer> map = new HashMap<>(10);
map.put(1,10);
map.put(2,20);
map.put(3,30);
map.put(4,30);
map.entrySet()
.stream()
.forEach(var->{
val key = var.getKey();
val value = var.getValue();
System.out.println("key:"+key+" value:"+value);
});
/**
stream 结果:
key:1 value:10
key:2 value:20
key:3 value:30
key:4 value:30
parallelStream 结果:
key:4 value:30
key:1 value:10
key:2 value:20
key:3 value:30
*/
中间操作
filter 筛选
map 提取
limit 截断
sorted 排序
List<Integer> list = Arrays.asList(2, 4, 1, 3, 7, 5, 9, 6, 8,7);
List<Integer> sortedList = list.parallelStream()
//筛选元素大于10
.filter(number-> number>5)
//递减
.sorted( (i1, i2) -> i2.compareTo(i1) )
//自然序列排序,递增
//.sorted()
.collect(Collectors.toList());
System.out.println(sortedList);
/**
[9, 8, 7, 7, 6]
*/
distinct 去重
List<Integer> list1 = Arrays.asList(2, 4, 1, 3, 7, 5, 9, 6, 8,7);
List<Integer> sortedList = list1.parallelStream()
//筛选元素大于10
.filter(number-> number>5)
//自然序列排序,递增
.sorted()
//去重
.distinct()
.collect(Collectors.toList());
/**
[6, 7, 8, 9]
*/
终端操作
forEach遍历
collect 返回集合
.collect(Collectors.toList());
count 返回long
long count =
//数据源
Dish.menu.stream()
//筛选
.filter(d->d.getCalories()>300)
//去重
.distinct()
//提取三个
.limit(3)
//生成
.count();
System.out.println(count);
菜单实体
package com.java8.stream.entity;
import lombok.Data;
import java.util.*;
@Data
public class Dish {
private final String name;
private final boolean vegetarian;
private final int calories;
private final Type type;
public Type getType() {
return type;
}
public enum Type { MEAT, FISH, OTHER }
public static final List<Dish> menu =
Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT),
new Dish("beef", false, 700, Dish.Type.MEAT),
new Dish("chicken", false, 400, Dish.Type.MEAT),
new Dish("french fries", true, 530, Dish.Type.OTHER),
new Dish("rice", true, 350, Dish.Type.OTHER),
new Dish("season fruit", true, 120, Dish.Type.OTHER),
new Dish("pizza", true, 550, Dish.Type.OTHER),
new Dish("prawns", false, 400, Dish.Type.FISH),
new Dish("salmon", false, 450, Dish.Type.FISH));
}