Rahul Anand
Rahul Anand

Reputation: 165

Convert List<List<Object>> to Map<String,String> Java 8

I have a List where OcrImageLocation contain List and String s3_id;

I just wanted to convert list to map which contain s3_id as key and image_location as value using java 8

public class PageLocationInfo {
   @JsonProperty("page_index")
   private String page_index;
   @JsonProperty("location")
   private String location;
   @JsonProperty("image_location")
   private String image_location;
}
public class OcrImageLocation {
   private List<PageLocationInfo> page_info;
   @JsonProperty("s3_id")
   private String s3_id;
}

Upvotes: 2

Views: 158

Answers (2)

Eran
Eran

Reputation: 394156

You can map each pair of OcrImageLocation and PageLocationInfo to a Map.Entry<String,String> of the corresponding s3_id + page_index and image_location:

Map<String, String> map =
    input.stream()
         .flatMap(oil -> oil.getPageInfo()
                            .stream()
                            .map(pli -> new SimpleEntry<>(oil.getS3Id() + pli.getPageIndex(),
                                                          pli.getImageLocation())))
         .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));

Upvotes: 2

Vikas
Vikas

Reputation: 7205

You can do with Stream as below,

Map<String, String> result = locationList.stream().map(e -> e.getPage_info().stream()
          .collect(Collectors.toMap(e1 -> e.getS3_id() + e1.getPage_index(),
                  PageLocationInfo::getImage_location)))
          .flatMap(e -> e.entrySet().stream())
          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

Upvotes: 0

Related Questions