I have a question and hope someone would help me improve my knowledge of Java Stream API.
My service receives data from another service via RabbitMQ as array like this:
[ {"deviceId":1,"userId":1},
{"deviceId":2,"userId":1},
{"deviceId":3,"userId":2},
{"deviceId":4,"userId":2},
{"deviceId":5,"userId":1},
{"deviceId":6,"userId":2},
... ]
What I need to do with this data is to collect it into List where User has userId and List of deviceId's. So from the data above it should be:
User {userId: 1, List<deviceId>: 1,2,5} & User {userId: 2, List<deviceId>: 3,4,6}
I do have a working solution but it is clumsy & I believe it all could be done way better with Java Stream API.
The solution is:
private List<User> parseDeviceData(JsonNode jsonNode) {
List<JsonNode> list = StreamSupport.stream(jsonNode.spliterator(), false)
.filter(this::validDeviceRecord) // checking for presence of deviceId & userId
.collect(Collectors.toList());
Map<Integer, ArrayList<Integer>> map = new HashMap<>();
for (JsonNode j : list) {
Integer id = j.get("deviceId").asInt();
Integer userId = j.get("userId").asInt();
ArrayList<Integer> l;
if (map.containsKey(userId)) {
l = map.get(userId);
} else {
l = new ArrayList<>();
}
l.add(id);
map.put(userId, l);
}
return map.entrySet().parallelStream()
.map(entry -> new User(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());
}
How could I do the same with streams? Thanks!