将对象列表的列表转换为地图 - 在java 8中使用lambdas [英] Convert List of List of Object to a map - using lambdas in java 8

查看:126
本文介绍了将对象列表的列表转换为地图 - 在java 8中使用lambdas的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有如下对象结构:

Order {
    int code;
    int id;
    List<Item>;
}

Item {
     int code;
     int quantity;
     List<Suborder>;
}

Suborder {
    int code;
    int quantity;
}

我有一个O的对象,我想要一个从代码到B的地图。怎么做正确的方法呢?

I have an object of O and I want a map from code to B. Whats the correct way to do this?

我尝试了什么:

1 - 不工作

order.getOrderItems().stream().flatMap(l -> l.getOrderItemSuborder().stream()).collect(Collectors.toMap(x -> x.getCode() , Function.identity())); // x.getCode() seems to be not available here  :( 

2 - 工作

order.getOrderItems().forEach(x -> x.getOrderItemSuborder().forEach(y -> suborderMap.put(y.getCode(),y)));

我不确定#2是否正确这样做。

I am not sure if #2 is right way to do it.

我如何让#1工作?

PS:从lambdas开始,可能是一个愚蠢的问题,但我不知道如果是:p

P.S. : Starting with lambdas, might be a stupid question, but i don't know that if it is :p

推荐答案

根据我的理解,我认为你需要像这个

From what I understand I think you need something like this

O order;
order.getAList().stream()
      .flatMap(a -> a.getBList().stream())
      .collect(toMap(b -> b.getCode(), b -> b));

当你第一次尝试时,你需要的是 b - > b ,我想你错过了lambda中那部分收集地图

When you did the first try, what you needed was b -> b, I think you missed out that part of the collect map in the lambda

这篇关于将对象列表的列表转换为地图 - 在java 8中使用lambdas的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆