I have a List, I need to convert it to List<Map<String, String>>.
For e.g. consider below scenario:
public class AnyClass() {
private String letter;
}
Now, suppose I have a list objectList which have multiple object with diff value of letter
List<AnyClass> objectList = new ArrayList();
objectList.add(new AnyClass("A"));
objectList.add(new AnyClass("B"));
objectList.add(new AnyClass("C"));
objectList.add(new AnyClass("D"));
now I want to convert it to List<Map<String, String>> using Stream in java 8.
I want to achieve the following:
List<Map<String, String>> listOfMaps = new ArrayList<>();
for(AnyClass object: objectList) {
listOfMaps.add(ImmutableMap.<String, String>builder()
.put("ConstantKey","ConstantValue")
.put("ConstatKey2", object.getLetter())
.build());
}
>Solution :
It’s a simple map() and collect():
List<Map<String, String>> listOfMaps = objectList.stream()
.map(o -> ImmutableMap.of(
"ConstantKey", "ConstantValue",
"ConstantKey2", o.getLetter()))
.collect(Collectors.toList());
You might want to extract the map construction to a separate method to keep the lambda a little cleaner.