Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split a list into multiple sublist based on element properties in Java

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

like image 876
kapil das Avatar asked Dec 19 '22 19:12

kapil das


1 Answers

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);
}
like image 71
halfbit Avatar answered Dec 21 '22 09:12

halfbit