2

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; } 
5
  • 2
    What are you going to do with duplicates? You can't have multiple values for the same s3_id key in your output Map. Commented Apr 30, 2020 at 4:52
  • 1
    Maybe you want a map of s3_id => list of image_locations, in other words Map<String, List<String>>? Commented Apr 30, 2020 at 4:57
  • In your OcrImageLocation s3_id maps to a list of PageLocationInfo. that means one s3_id map with multiple image_locations. Since Map doesn't allow duplicate keys what you are asking is confusing. Commented Apr 30, 2020 at 5:05
  • Actually i am thinking to make s3_id + page_index as key as it would be unique always Commented Apr 30, 2020 at 5:11
  • Map<String,String> as per this, May I know one s3_id fill contain only one image location. if is true the it has sense otherwise data will be overridden. It is is not then Map<String, List<String>> Commented Apr 30, 2020 at 6:24

2 Answers 2

2

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)); 
Sign up to request clarification or add additional context in comments.

Comments

0

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

3 Comments

Collecting twice is not a good idea. Actually the first collect is redundant. You can flatmap the uncollected stream.
And if you do that, you'll end up with Eran's asnwer
I came to this solution after spending almost 15 mins. Yes, I agree that collecting twice is not a good idea. Erans answer is perfect.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.