java8 Stream API各种流操作应用(2)

Stream API大概有筛选、切片、映射、查找、匹配和归约等操作,现在我们都实际应用下

import java.util.*;

public class Dish {

    private final String name;
    private final boolean vegetarian;
    private final int calories;
    private final Type type;

    public Dish(String name, boolean vegetarian, int calories, Type type) {
        this.name = name;
        this.vegetarian = vegetarian;
        this.calories = calories;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public boolean isVegetarian() {
        return vegetarian;
    }

    public int getCalories() {
        return calories;
    }

    public Type getType() {
        return type;
    }

    public enum Type { MEAT, FISH, OTHER }

    @Override
    public String toString() {
        return name;
    }

    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));
}



filter筛选

//筛选
		//List<Dish> vegetarianMenu = Dish.menu.stream().filter(Dish::isVegetarian).collect(toList());
		Dish.menu.stream().filter(Dish::isVegetarian).collect(toList()).forEach(System.out::println);

List<Integer> numbers = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
		numbers.stream().filter(i -> i % 2 == 0).distinct().forEach(System.out::println);

limit截短流

//limit截短流
		Dish.menu.stream().filter(d -> d.getCalories() > 300).limit(3).collect(toList()).forEach(System.out::println);


//skip跳过前面元素
		Dish.menu.stream().filter(d -> d.getCalories() > 300).skip(3).collect(toList()).forEach(System.out::println);



//映射  应getName类型String,map输出流类型Stream<String>
		Dish.menu.stream().map(Dish::getName).collect(toList()).forEach(System.out::println);



//菜单中每个名称长度
		Dish.menu.stream().map(Dish::getName).map(String::length).collect(toList()).forEach(System.out::println);


//flatMap流的扁平化:单个numbers2.stream().map流合成一个流,代码功能:将2个数组合并新的数组并过滤将各个数组中的单个元素之和被3整除后的结果
		List<Integer> numbers1 = Arrays.asList(1, 2, 3);
		List<Integer> numbers2 = Arrays.asList(3, 4);
		List<Integer[]> pairs = numbers1.stream().flatMap(i -> { // System.out.println(i+"--");
			return numbers2.stream().filter(j -> (i + j) % 3 == 0).map(j -> {
				//System.out.println(i + " " + j);
				return new Integer[] { i, j };
			});
		}).collect(toList());

// 匹配anyMatch,allMatch,noneMatch
		// anyMatch谓词 Dish.menu.stream是否有一个匹配 anyMatch谓词
		if (Dish.menu.stream().anyMatch(Dish::isVegetarian)) {
			System.out.println("The menu is (somewhat) vegetarian friendly!!");
		}

		// allMatch Dish.menu.stream是否都能匹配 allMatch谓词
		if (Dish.menu.stream().allMatch(Dish::isVegetarian)) {
			System.out.println("The menu is (somewhat) vegetarian friendly!!");
		}

		// noneMatch Dish.menu.stream没有匹配 noneMatch谓词
		if (Dish.menu.stream().noneMatch(Dish::isVegetarian)) {
			System.out.println("The menu is (somewhat) vegetarian friendly!!");
		}

		// 查找元素findAny,findFirst
		// findAny返回当前流中的任意元素
		// Dish.menu.stream().filter(Dish::isVegetarian).findAny();
		// ifPresent是否返回一个
		Dish.menu.stream().filter(Dish::isVegetarian).findAny().ifPresent(d -> System.out.println(d.getName()));
		Optional<Integer> firstSquareDivisibleByThree = Arrays.asList(1, 2, 3, 4, 5).stream().map(x -> x * x).filter(x -> x % 3 == 0)
				.findFirst(); // 9



// 归约reduce
		// int count = Dish.menu.stream().map(d -> 1).reduce(0, (a, b) -> a +
		// b);
		System.out.println(Dish.menu.stream().map(d -> 1).reduce(0, (a, b) -> {
			//System.out.println(a+" "+b);
			return a + b;
		}));
		//reduce计算形式  1*5*2*3
		System.out.println(Arrays.asList(5,2,3).stream().reduce(1, (a, b) -> { System.out.println(a+" "+b);  return a * b;}));
		//reduce计算形式 0+5+2+3
		System.out.println(Arrays.asList(5,2,3).stream().reduce(0, Integer::sum));
     
		//5 重复lambda参数比较 计算形式  0,5-->5  5,2-->5   5,3-->5  
		System.out.println(Arrays.asList(5,2,3).stream().reduce(0, Integer::max));
		
		//0  重复lambda参数比较 计算形式  0,5-->0  0,2-->0   0,3-->0  
		System.out.println(Arrays.asList(5,2,3).stream().reduce(0, Integer::min));




















猜你喜欢

转载自blog.csdn.net/luozhonghua2014/article/details/78824577