Skip to content
Advertisement

Java use streams map to return desired JSON Structure

I’m new to Java I have an array like below

[{'roleName': "driver", "name": "Hub"},{'roleName': "hoc", "name": "Org"},{'roleName': "hubManager", "name": "Hub"}]

I have to format the same into below structure

 {
    Org :{
        role : ["hoc"]
    }
    Hub: {
        role :
            ["driver","hubManager"]
        }
 }

Please help me how we can do this with Java streams

I have tried the below

List<String> roles = roleLevels
                .stream()
                .map(c -> c.getRoleName()).collect(Collectors.toList());

But that’s not the expected result

Advertisement

Answer

Use groupingBy with downstream Collector:

Map<String, List<String>> result = 
    roleLevels.stream()
              .collect(Collectors.groupingBy(RoleManager::getName, 
                                             Collectors.mapping(RoleManager::getRole,
                                                                Collectors.toList())));
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement