I have a list of objects and I want to convert it into a Map which is grouped by one variable in the object. Below is lengthy code I got to. Can someone help me do this in one line?
List<Document> all = repo.getAllDocuments(); List<String> ids = all.parallelStream() .map(obj -> obj.getFor().getOpp().Id()) .collect(Collectors.toList()); Map<String, List<Document>> map = new HashMap<>(); ids.forEach(id -> map.put(id, all.parallelStream() .filter(obj -> obj.getFor().getOpp().getId().equals(id)) .collect(Collectors.toList())));
Answer
Try this:
Map<String, List<Document>> map = repo.getAllDocuments() .stream() .collect(Collectors.groupingBy(doc -> doc.getFor().getOpp().getId()));