问题
I get a list of object arrays that I need to group. The arrays contain different types of objects. Here is an example:
List<Object[]> resultList = query.getResultList(); // call to DB
// Let's say the object array contains objects of type Student and Book
// and Student has a property Course.
// Now I want to group this list by Student.getCourse()
Map<String, Object[]> resultMap = resultList.stream().collect(Collectors.groupingBy(???));
What do I provide to the Collectors.groupingBy()
method ?
The Student object is at index 0 in the object array.
回答1:
groupingBy
will by default give you a Map<String, List<Object[]>>
in your case, because you will group arrays based on their student's course value.
So you need to group by the course value of the student in the array. The function you will apply will hence be:
o -> ((Student)o[0]).getCourse()
thus the grouping by implementation becomes:
Map<String, List<Object[]>> resultMap =
resultList.stream().collect(groupingBy(o -> ((Student)o[0]).getCourse()));
As an aside, you may want to use a class to have typed data and to avoid the cast, that could possibly throw an exception at runtime.
You could also perform the grouping by at the database level.
来源:https://stackoverflow.com/questions/31534661/groupingby-list-of-arrays