Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
229 views
in Technique[技术] by (71.8m points)

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...