Вот один из способов сделать это без использования POJO:
String input = "{" +
" \"data\": [\n" +
" {\n" +
" \"userId\": \"userId1\",\n" +
" \"role\": \"admin\",\n" +
" \"accesscode\": \"000008\"\n" +
" },\n" +
" {\n" +
" \"userId\": \"userId1\",\n" +
" \"role\": \"admin\",\n" +
" \"accesscode\": \"000007\"\n" +
" },\n" +
" {\n" +
" \"userId\": \"userId2\",\n" +
" \"role\": \"analyst\",\n" +
" \"accesscode\": \"000001\"\n" +
" }\n" +
" ]\n" +
"}";
ObjectMapper mapper = new ObjectMapper();
Map<String, List<Map<String, String>>> data = mapper.readValue(input,
new TypeReference<Map<String, List<Map<String, String>>>>() {/**/});
Map<String, List<Map<String, Object>>> combinedData = new HashMap<>();
combinedData.put("data", data.get("data").stream()
.collect(Collectors.groupingBy(
u -> Arrays.asList(u.get("userId"), u.get("role")),
Collectors.mapping(u -> u.get("accesscode"), Collectors.toList())))
.entrySet().stream()
.map(e -> {
Map<String, Object> user = new LinkedHashMap<>();
user.put("userId", e.getKey().get(0));
user.put("role", e.getKey().get(1));
user.put("accesscode", e.getValue());
return user;
})
.collect(Collectors.toList()));
String output = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(combinedData);
System.out.println(output);
Вывод
{
"data" : [ {
"userId" : "userId2",
"role" : "analyst",
"accesscode" : [ "000001" ]
}, {
"userId" : "userId1",
"role" : "admin",
"accesscode" : [ "000008", "000007" ]
} ]
}