java8的stream用户java
数据准备:数组
public class Dish { public String name; //菜的名称 public Boolean vegetaian; //是否为素 public Integer calories; //卡路里 public Type type; //类型(肉 鱼 其余) public Dish() { } public Dish(String name, Boolean vegetaian, Integer calories, Type type) { this.name = name; this.vegetaian = vegetaian; this.calories = calories; this.type = type; } public enum Type {MEAT, FISH, OTHER} //肉 鱼 其余 }
public class DishList { public static List<Dish> getDishList() { List<Dish> dishList = 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, 300, Dish.Type.FISH), new Dish("salmon", false, 450, Dish.Type.FISH) ); return dishList; } }
1:filterapp
/** * filter 过滤结果为true的 * 过滤“calories:卡路里”小于500的 */ @Test public void filter() { List<Dish> dishList = DishList.getDishList(); List<Dish> collect = dishList.stream().filter(dish -> dish.getCalories() < 500).collect(Collectors.toList()); collect.forEach(System.out::println); }
2:distinctide
/** * 去重:过滤元素相同的 */ @Test public void distinct() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 1, 2); list.stream().distinct().forEach(System.out::println); }
3: skipui
/** * skip 跳过前n个 */ @Test public void skip() { List<Dish> dishList = DishList.getDishList(); dishList.stream().skip(5).forEach(System.out::println); }
4: limitthis
/** * limit 只保留前n个 */ @Test public void limit() { List<Dish> dishList = DishList.getDishList(); dishList.stream().limit(5).forEach(System.out::println); }
5: mapspa
/** * map 映射 */ @Test public void map() { List<Dish> dishList = DishList.getDishList(); Function<Dish, String> function1 = dish -> dish.getName() + ","; //转换的结果能够为任意类型与形式 Function<Dish, String> function2 = Dish::getName; List<String> collect = dishList.stream().map(function1).collect(Collectors.toList()); collect.forEach(System.out::println); }
6: flatMapcode
/** * flatMap:扁平化 * 获取每个元素,并去重
对hello,world分割去重 */
@Test
public void filter3() {
String[] words = {"hello", "world"};
// 将words换成流,stream中有 "hello","world" 两个元素
Stream<String> stream = Arrays.stream(words);
// 将stream中每一个元素映射成“字符串数组” ,stream1中有“h,e,l,l,o”,"w,o,r,l,d"
Stream<String[]> stream1 = stream.map(item -> item.split(""));
// 将流中的每一个值都换成另外一个流,而后把全部的流连接成1个流(将stream1映射成“h,e,l,l,o,w,o,r,l,d”)
Stream<String> stream2 = stream1.flatMap(Arrays::stream);
stream2.distinct().forEach(System.out::println);
}
Matchblog
7:allMatchip
/** * 全匹配 * 全部的dish的calories都<400吗? */ @Test public void allMatch() { List<Dish> dishList = DishList.getDishList(); boolean b = dishList.stream().allMatch(item -> item.getCalories() < 400); System.out.println(b); }
8:anyMatch
/**
* 存在一个匹配
* 至少1个dish的calories都<400吗?
*/
@Test
public void anyMatch() {
List<Dish> dishList = DishList.getDishList();
boolean b = dishList.stream().anyMatch(item -> item.getCalories() < 400);
System.out.println(b);
}
9:noneMatch
/** * 不存在匹配 * 全部的dish的calories都不<400吗? */ @Test public void noneMatch() { List<Dish> dishList = DishList.getDishList(); boolean b = dishList.stream().noneMatch(item -> item.getCalories() < 400); System.out.println(b); }
Find
10:findAny
@Test public void findAny() { List<Dish> dishList = DishList.getDishList(); Dish dish = dishList.stream().findAny().orElse(new Dish()); System.out.println(dish); }
11:findFirst
@Test public void findFirst() { List<Dish> dishList = DishList.getDishList(); Dish dish = dishList.stream().findFirst().orElse(new Dish()); System.out.println(dish); }
Reduce 规约(将流中的元素组合,规约成一个值)
12:reduce
@Test
public void reduce1() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
IntBinaryOperator operator = (s1, s2) -> s1 + s2;
OptionalInt reduce = list.stream().mapToInt(Integer::intValue).reduce(operator);
int asInt = reduce.getAsInt();
System.out.println(asInt);
//IntBinaryOperator 的 int applyAsInt(int left, int right); 方法,接受两个参数
//mapToInt(Integer::intValue) 将int值拆箱
//getAsInt 从Optional取出值(若是值不存在则抛出异常) 使用 int asInt = reduce.orElse(0); 获取值,或者使用isPresient判断再取值
}
13:reduce
@Test public void reduce2() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); IntBinaryOperator operator = (s1, s2) -> s1 + s2; int reduce = list.stream().mapToInt(Integer::intValue).reduce(0,operator); //使用默认值
//int reduce = list.stream().mapToInt(Integer::intValue).reduce(0,Integer::sum) //Integer::sum 求和 Integet::max 最大值 Integer::min 最小值
System.out.println(reduce);
}
14:boxed
/** * 包装与拆箱 */ @Test public void boxed() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); IntStream intStream = list.stream().mapToInt(Integer::intValue); //拆箱 Stream<Integer> boxed = intStream.boxed(); //包装 List<Integer> collect = boxed.collect(Collectors.toList()); }
Optional (待完善)
15:Optional
/** * Optional 包装 */ @Test public void optional() { //包含元素为null的Optional Optional empty = Optional.empty(); boolean present = empty.isPresent(); // false //包含元素必须不为null Optional<String> of = Optional.of("optional"); //包含元素为null调用 empty()方法,不为null调用 of()方法 Optional<String> optional = Optional.ofNullable("optional"); }
Collectors
16:toList
/** * toList
* 筛选“vegetaian”,-> list */ @Test public void toList() { List<Dish> dishList = DishList.getDishList(); List<Dish> collect = dishList.stream().filter(Dish::getVegetaian).collect(Collectors.toList()); }
17:toSet
/** * toSet
*将dish -> name->set */ @Test public void toSet() { List<Dish> dishList = DishList.getDishList(); Set<String> collect = dishList.stream().map(Dish::getName).collect(Collectors.toSet()); }
18:toMap
/** * toMap
* key:name value:dish */ @Test public void toMap() { List<Dish> dishList = DishList.getDishList(); Map<String, Dish> collect = dishList.stream().collect(Collectors.toMap(Dish::getName, Function.identity())); }
19:toConcurrentMap
/** * toConcurrentMap * key:name value:自身 ->存放到ConcurrentMap中 */ @Test public void toConcurrentMap() { List<Dish> dishList = DishList.getDishList(); ConcurrentMap<String, Dish> collect = dishList.stream().collect(Collectors.toConcurrentMap(Dish::getName, Function.identity())); }
20:averaging
/** * 平均值
* 返回的都是double类型,区别在“参数”限制 */ @Test public void averaging() { List<Dish> dishList = DishList.getDishList(); Double aInt = dishList.stream().collect(Collectors.averagingInt(Dish::getCalories)); Double aDouble = dishList.stream().collect(Collectors.averagingDouble(Dish::getCalories)); Double aLong = dishList.stream().collect(Collectors.averagingLong(Dish::getCalories)); }
21:collectingAndThen
/** * 附加动做 * collectingAndThen(Collector<T,A,R> downstream,Function<R,RR> finisher) * Collector 执行的结果做为 Function 的入参 * 备注:Collectors调用的方法返回的便是Collector类型 */ @Test public void collectingAndThen() { List<Dish> dishList = DishList.getDishList(); String collect = dishList.stream().collect(Collectors.collectingAndThen(Collectors.averagingInt(Dish::getCalories), item -> "结果为:" + item)); System.out.println(collect); }
22:unmodifiableList
/** * 只读 * */ @Test public void unmodifiableList() { List<Dish> dishList = DishList.getDishList(); List<Dish> collect = dishList.stream().collect(Collectors.collectingAndThen(Collectors.toList(),Collections::unmodifiableList)); }
23: