Java8List对象中的List匹配元素 返回当前匹配后的数据(含外数组)

需求:获取lols中的player某个元素

import com.alibaba.fastjson.JSONObject;
import lombok.*;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Demo {


    @Builder
    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ToString
    static class LOL{
        //赛区
        private String area;
        //战队名称
        private String teamName;
        //战队选手
        List player;

    }
    private static List lols= new ArrayList<>();;
    static  {
         lols.add( new LOL( "LPL", "IG", Arrays.asList( "TheShy","JK","Rk","BaoLan","Ning") ));
         lols.add( new LOL( "LPL", "FPX", Arrays.asList( "Doinb","GimGoon","Tian","Lwx","Crisp") ));
         lols.add( new LOL( "LCK", "SKT", Arrays.asList( "faker","khan","child","teddy","mata") ));
    }
    public static void main(String[] args) {
        List newLols=new ArrayList<>();

        //我要从所有的赛区里找到指定选手的名字 也就是 在List下的list元素匹配返回当前list(外圈)
        //筛选faker在那个战队
        String keyWord="faker";
        List> result = lols.stream().map( res -> {
            return res.getPlayer().stream().filter( b ->
                    b.split( "-" )[0].equals( keyWord )
            ).map( b -> {
                return res;
            } ).collect( Collectors.toList() );
        } ).filter( res -> !CollectionUtils.isEmpty( res ) ).collect( Collectors.toList() );
        result.forEach( item->newLols.addAll( item ) );
        System.out.println( JSONObject.toJSON( newLols  ) );
    }
}

输出结果为:

[{"area":"LCK","teamName":"SKT","player":["faker","khan","child","teddy","mata"]}]
image.png

你可能感兴趣的:(Java8List对象中的List匹配元素 返回当前匹配后的数据(含外数组))