我在下面输入了Map,并希望使用Java流将其转换为Map(即Map>),任何帮助都将适用于
Map<String, Object> objectmetainfo = new HashMap();
objectmetainfo.put("metainfo.id", "id");
objectmetainfo.put("metainfo.title", "title");
objectmetainfo.put("metainfo.description", "description");
objectmetainfo.put("metainfo.userDetails.user.id", "id");
objectmetainfo.put("metainfo.userDetails.user.firstName", "firstName");
objectmetainfo.put("metainfo.userDetails.user.lastName", "lastName");
objectmetainfo.put("metainfo.userDetails.user.email", "email");
objectmetainfo.put("metainfo.userDetails.user.phone", "phone");
objectmetainfo.put("metainfo.userDetails.userSupervisor.id", "id");
objectmetainfo.put("metainfo.userDetails.userSupervisor.firstName", "firstName");
objectmetainfo.put("metainfo.userDetails.userSupervisor.lastName", "lastName");
objectmetainfo.put("metainfo.userDetails.userSupervisor.email", "email");
objectmetainfo.put("metainfo.userDetails.userSupervisor.phone", "phone");
--------- many more ---------
objectmetainfo.put("metainfo.user_id", "id");
objectmetainfo.put("metainfo.user_name", "name");
我想将此地图转换为Map,如下所示:
{"user":{"id":"id", "firstName":"firstName", "lastName":"lastName", "email":"email", "phone":"phone"}, "userSupervisor":{"id":"id", "firstName":"firstName", "lastName":"lastName", "email":"email", "phone":"phone}}
{"additional":{"user_id":"user_id", "user_name":"user_name"}}
答案 0 :(得分:1)
我已经使用Pair(导入javafx.util.Pair;)来获取Pair<String, Pair<String, Object>>
这个想法很简单,首先获取Map的entrySet,然后根据条件创建单个Pair。 使用GroupingBy合并结果(以获取Map>)并将其收集到Map中。
Map<String, Map<String, Object>> answer =
objectmetainfo.entrySet()
.stream()
.map(e-> makePair(e))
.collect(Collectors.groupingBy(e-> e.getKey(), Collectors.toMap(e-> e.getValue().getKey(), e-> e.getValue().getValue()) ));
配对功能:
private static Pair<String, Pair<String, Object>> makePair(Map.Entry<String, Object> mapEntry){
final String[] s = mapEntry.getKey().split("\\.");
return
mapEntry.getKey().contains("metainfo.userDetails.") ? new Pair(s[2],
new Pair(s[3], mapEntry.getValue())) :
new Pair("additional",
new Pair(s[1], mapEntry.getValue()))
;
}
将键拆分为“。” (正则表达式“ //。”),然后根据条件进行配对。
PS:请给变量取有意义的名称。