groupingby list of arrays

假如想象 提交于 2021-02-11 08:10:37

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!