java8 stream
Posted Draymond
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java8 stream相关的知识,希望对你有一定的参考价值。
java8的stream用户
数据准备:
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:filter
/** * 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:distinct
/** * 去重:过滤元素相同的 */ @Test public void distinct() { List<Integer> list = Arrays.asList(1, 2, 3, 4, 1, 2); list.stream().distinct().forEach(System.out::println); }
3: skip
/** * skip 跳过前n个 */ @Test public void skip() { List<Dish> dishList = DishList.getDishList(); dishList.stream().skip(5).forEach(System.out::println); }
4: limit
/** * limit 只保留前n个 */ @Test public void limit() { List<Dish> dishList = DishList.getDishList(); dishList.stream().limit(5).forEach(System.out::println); }
5: map
/** * 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: flatMap
7:
8:
9:
10:
以上是关于java8 stream的主要内容,如果未能解决你的问题,请参考以下文章