Java lambda list 转 map,map的key为list对象的任意字段

public class Table<T,R> {



    public static <T,R>  Map<R,T> mapBy(Class clazz, Function<T,R>
            function){
        Object o = GameLibraryData.mapByClassName.get(clazz.getSimpleName());
        if(o instanceof  List){
            List<T> dataList = (List<T>)o;
            return mapBy(dataList, function);
        }
        return  null;
    }

    public static <T,R>  Map<R,T> mapBy(List<T> dataList, Function<T,R>
            function){
        return dataList.stream().collect(Collectors.toMap(function, a -> a, (k1, k2) -> k1));
    }



    public static void main(String[] args) {
        List<GameLibraryFileReader.Test> testList = new ArrayList<>();
        testList.add(new GameLibraryFileReader.Test("test",1));
        testList.add(new GameLibraryFileReader.Test("test2",2));
        testList.add(new GameLibraryFileReader.Test("test3",3));
        testList.add(new GameLibraryFileReader.Test("test4",4));
        testList.add(new GameLibraryFileReader.Test("test5",5));
        Map<Integer, GameLibraryFileReader.Test> integerTestMap = Table.mapBy(testList, GameLibraryFileReader.Test::getAge);
        Map<String, GameLibraryFileReader.Test> stringTestMap = Table.mapBy(testList, GameLibraryFileReader.Test::getName);
        System.out.println();
    }



}

可以自由的根据 list 中的对象转为map,方便从list中获取对应的数据,而且可以传入任意list存储对象的字段,获取传入字段分类好的map

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值