user1491987
user1491987

Reputation: 751

Using stream to convert list of strings to list of maps with custom key

Given list of strings like this:

"Y:Yes",
"N:No",
"A:Apple"

I have something like

Map updated = values.stream().map(v -> v.split(":")).collect(Collectors.toMap(v1 -> v1[0],v1->v1.length>1?v1[1]:v1[0]));

But this gives me map as:

{
"Y":"Yes",
"N":"No",
"A":"Apple"
}

How can I get a list of maps as such:

[
{
  name:"Y",  
  display:"Yes"
},
{
  name:"N",  
  display:"No"
},
{
  name:"A",  
  display:"Apple"
}
]

Upvotes: 1

Views: 612

Answers (3)

Lino
Lino

Reputation: 19926

You can use following if you're still using Java8, if you happen to use Java9 then have a look at Federicos answer:

final List<Map<String,String>> updated = values.stream()
    .map(v -> v.split(":"))
    .map(arr -> {
        Map<String, String> map = new HashMap<>();
        map.put("name", arr[0]);
        map.put("display", arr[1]);
        return map;
    })
    .collect(Collectors.toList());

Upvotes: 1

fps
fps

Reputation: 34460

If you are using Java 9, you can use the new immutable map static factory methods, as follows:

List<Map<String, String>> updated = values.stream()
    .map(v -> v.split(":"))
    .map(a -> Map.of("name", a[0], "display", a[1]))
    .collect(Collectors.toList());

Upvotes: 2

DWilches
DWilches

Reputation: 23015

As you want to get a List, not a map, your last function call cannot be Collectors.toMap, needs to be Collectors.toList. Now, each invocation to the map method should generate a new Map, so something like this would do:

List updated = values.stream()
    .map(v -> {
        String[] parts = v.split(":");
        Map<String, String> map = new HashMap<>();
        map.put("name", parts[0]);
        map.put("display", parts[1]);
        return map;
    )
    .collect(Collectors.toList());

Some people would prefer:

List updated = values.stream()
    .map(v -> {
        String[] parts = v.split(":");
        return new HashMap<>() {{
            put("name", parts[0]);
            put("display", parts[1]);
        }};
    )
    .collect(Collectors.toList());

which creates an extra helper class. Or if you can use Guava:

List updated = values.stream()
    .map(v -> {
        String[] parts = v.split(":");
        return ImmutableMap.of("name", parts[0], "display", parts[1]);
    )
    .collect(Collectors.toList());

BTW: In the examples I used Listbut the complete type of what you describe would be List<Map<String, String>>.

Upvotes: 1

Related Questions