简体   繁体   中英

Java 8 groupingBy for a list of Maps

I have a list of map for which i want to group them by name

List<Map> allObjs = new ArrayList<Map>();
Map<String, Object> src = new HashMap();
src.put("name", "asset1");
src.put("description", "desc1" );
src.put("definition", "def1" );

Map<String, Object> src2 = new HashMap();
src2.put("name", "asset1");
src2.put("description", "desc2" );
src2.put("definition", "def2" );
allObjs.add(src);
allObjs.add(src2);

I tried grouping them by

Map<Object, List<Map>> result = allObjs.stream().collect(Collectors.groupingBy(p -> p.get("name")));

What i want is

{
 name=asset1,
 description=["desc1","desc2"],
 definition=["def1","def2"]
}

I want all the other keys to be grouped in a list But what i got is

{asset1=[
            {name=asset1, description=desc1, definition=def2},
            {name=asset1, description=desc2, definition=def2}
        ]
}

How do i group all the other keys except name to a list like expected above?

You can use groupBy with mapping to get the desired result, just values would be of single type only,

Map<String, Set<String>> collect1 = allObjs.stream()
                .flatMap(m -> m.entrySet().stream())
                .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toSet())));

Result:

{
 name=[asset1],
 description=[desc1,desc2],
 definition=[def1,def2]
}

groupingBy will group the items based on a key. It does not do a merge of two maps. This is one of the ugly ways to achieve what you want.

Given

List<Map<String, String>> allObjs = new ArrayList<>();
Map<String, String> src = new HashMap();
src.put("name", "asset1");
src.put("description", "desc1" );
src.put("definition", "def1" );

Map<String, String> src2 = new HashMap();
src2.put("name", "asset1");
src2.put("description", "desc2" );
src2.put("definition", "def2" );
allObjs.add(src);
allObjs.add(src2);

One way to do is this. Create two classes, representing existing structure and final output structure

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class SomeClass {
    private String name;
    private String description;
    private String definition;
}

@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class NewClass {
    private String name;
    private List<String> description;
    private List<String> definition;
}

Then this code should get the output u desired

final List<NewClass> collect = allObjs.stream()
        .map(entry -> new SomeClass(entry.get("name"), entry.get("description"), entry.get("definition")))
        .collect(Collectors.toList())
        .stream()
        .collect(Collectors.groupingBy(SomeClass::getName))
        .entrySet()
        .stream()
        .map(entry -> {
            final List<String> descriptions = entry.getValue().stream().map(SomeClass::getDescription).collect(Collectors.toList());
            final List<String> definitions = entry.getValue().stream().map(SomeClass::getDefinition).collect(Collectors.toList());
            return new NewClass(entry.getKey(), descriptions, definitions);
        }).collect(Collectors.toList());

End result will be a list of type NewClass . Each entry in the list will have the desired output with a unique key. You need to incorporate a lot of null checks since it is a Map we are dealing with.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM