Is there a way to split a list to multiple list?. Given list into two or more list based on a particular condition of it elements.
final List<AnswerRow> answerRows= getAnswerRows(.........);
final AnswerCollection answerCollections = new AnswerCollection();
answerCollections.addAll(answerRows);
The AnswerRow has properties like rowId, collectionId
based on collectionId i want to create one or more AnswerCollections
If you just want to group elements by collectionId
you could try something like
List<AnswerCollection> collections = answerRows.stream()
.collect(Collectors.groupingBy(x -> x.collectionId))
.entrySet().stream()
.map(e -> { AnswerCollection c = new AnswerCollection(); c.addAll(e.getValue()); return c; })
.collect(Collectors.toList());
Above code will produce one AnswerCollection
per collectionId
.
With Java 6 and Apache Commons Collections, the following code produce the same results as the above code using Java 8 streams:
ListValuedMap<Long, AnswerRow> groups = new ArrayListValuedHashMap<Long, AnswerRow>();
for (AnswerRow row : answerRows)
groups.put(row.collectionId, row);
List<AnswerCollection> collections = new ArrayList<AnswerCollection>(groups.size());
for (Long collectionId : groups.keySet()) {
AnswerCollection c = new AnswerCollection();
c.addAll(groups.get(collectionId));
collections.add(c);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With