Convert List of List of Object to a map - using lambdas in java 8

妖精的绣舞 提交于 2019-12-25 18:19:21

问题


I have object structure like below:

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

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

Suborder {
    int code;
    int quantity;
}

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

What I tried :

1 - Not working

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 - Working

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

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

How can i make #1 working?

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


回答1:


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

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



来源:https://stackoverflow.com/questions/40213731/convert-list-of-list-of-object-to-a-map-using-lambdas-in-java-8

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!