Java8 Stream 流使用场景和常用操作

JAVA8内置的函数式编程接口应用场景和方式

pojo类对象和默认创建list的方法

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.ArrayList;
import java.util.List;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class DotaHero {

    private String name;
    private String kind;
    private String sex;

    /**
     * 返回一个不同元素的数组
     * @return
     */
    public static List<DotaHero> bulidDiffObjectList(){
        List<DotaHero> list = new ArrayList<>();
        list.add(new DotaHero("影魔", "敏捷", "男"));
        list.add(new DotaHero("小黑", "敏捷", "女"));
        list.add(new DotaHero("马尔斯", "力量", "男"));

        return list;
    }
}

测试类初始化一个List:

public class StreamTest {

    private List<DotaHero> dotaHeroes;

    @Before
    public void init(){
        dotaHeroes = DotaHero.bulidDiffObjectList();
    }


将根据list转换为该list对象中的一个属性映射该对象,name属性唯一的情况

@Test
    public void list2MapValueObject(){
        Map<String, DotaHero> nameMapDotaHero = dotaHeroes.stream().collect(Collectors.toMap(DotaHero::getName, d -> d));
        nameMapDotaHero.forEach((k,v) -> System.out.format("key=%s, value=%s
", k, v));
    }

 

将根据list转换为该list对象中的一个属性映射该对象,kind属性不唯一的情况Collectors.toMap 对于重复的key会抛出IllegalStateException异常

当key值不唯一时,通过Collectors.groupingBy将list转换成key映射list对象的格式:

/**
     * 将根据list转换为该list对象中的一个属性映射该对象
     * kind属性不唯一的情况
     */
    @Test
    public void list2MapValueList(){
        /*
        Collectors.toMap 对于重复的key会抛出IllegalStateException异常
        Map<String, DotaHero> nameMapDotaHero = dotaHeroes.stream().collect(Collectors.toMap(DotaHero::getKind, d -> d));
        nameMapDotaHero.forEach((k,v) -> System.out.format("key=%s, value=%s
", k, v));
        */
        // 当key值不唯一时,通过Collectors.groupingBy将list转换成key映射list对象的格式
        Map<String, List<DotaHero>> nameMapDotaHeroList = dotaHeroes.stream().collect(Collectors.groupingBy(DotaHero::getKind));
        nameMapDotaHeroList.forEach((k,v) -> System.out.format("key=%s, value=%s
", k, v));
    }

TODO 待写

flatMap

reduce

来源:

https://juejin.im/post/5cc124a95188252d891d00f2

https://mp.weixin.qq.com/s?__biz=MzI4Njg5MDA5NA==&mid=2247485508&idx=2&sn=a686a128ccbcfa1fcc000d8b9de14155&chksm=ebd74945dca0c05378c3083c6efda294ea11db25705436d08a6d6af4e82993cac99804ee1553&scene=0&xtrack=1&key=e5cd714fdda6b3aa961c90d5ceabf9b7d0f94dc88c73660c8794d57ea39a0ca44d0d09c268b6f61f951cf93c4ea327cb78a38248b4af27654602be675c377cd64ed280e4bc1b7438d2e4ddc57d559009&ascene=1&uin=ODEzMzE3OTc%3D&devicetype=Windows+10&version=62060833&lang=zh_CN&pass_ticket=fhXegoayg6%2BVSA6CJfCpSIPnWPJWR0l8dZnuI2R7r4U%3D

原文地址:https://www.cnblogs.com/theRhyme/p/10768367.html