2

I know how to convert List<Object> into Map<String,String> as you can see in this code:

Map<Long, String> divMap = divs.stream()
  .collect(Collectors.toMap(Div::getId, Div::getName));

The output of this is:

"1": "A", "2": "B"

But I want to return List<Map<String,String>> with the output given below:

["id":"1",Name="A"] ["id":"2",Name="B"]

2
  • Try using Map<String, String> result1 = list.stream().collect( Collectors.toMap(string1, string2));, Collectors.toMap is an API fpr doing that Commented Aug 5, 2017 at 20:53
  • Please read the question carefully this is what i was doing but i want to return List <Map<String,String> not Map<String,String> Commented Aug 5, 2017 at 21:03

2 Answers 2

5

The easiest way would be to help yourself by writing a separate toMap helper method that converts a Div into a Map<String, String>.

private Map<String, String> toMap(Div div) {
    Map<String, String> result = new HashMap<>();
    result.put("id", div.getId().toString());
    result.put("name", div.getName());
    return result;
}

...and everything becomes much easier then:

List<Map<String, String>> divMap = divs.stream()
  .map(this::toMap)
  .collect(Collectors.toList());

Also, it looks like you are trying to reinvent a wheel. Consider using some serialization/deserialization libraries.

Sign up to request clarification or add additional context in comments.

Comments

2

You can use Stream's reduce method, like:

final List<Div> divs = Arrays.asList(
       new Div("1", "A"),
       new Div("2", "B")
);

final List<Map<String, String>> result = divs.stream()
       .reduce(new ArrayList<>(), (list, div) -> {
            list.add(new HashMap<String, String>() {{
               put("id", div.getId());
               put("name", div.getName());
            }});
            return list;
        }, (a, b) -> a);

Reduce method expects 3 parameters:

  • initial value (empty list in this case)
  • BiFunction that provides 2 parameters: accumulator (type List<Map<String,String>> in your case) and current value taken from stream iteration (Div object) and returns a value of accumulator type
  • comparator function (in this case lambda (a,b) -> a is enough.

This approach pretty similar to folding known from functional programming.

2 Comments

The reduce is an overkill, check my answer :)
@GrzegorzPiwowarek Indeed, thumbs up for more clever approach :D :+1: I don't know why I thought of reducing in the very first place :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.