如何使用流和&amp ;;将列表中的对象按属性分组到其他列表中Java 8? [英] How to Group Objects in a List into other Lists by Attribute using streams & Java 8?

查看:653
本文介绍了如何使用流和&amp ;;将列表中的对象按属性分组到其他列表中Java 8?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将包含 time 属性的对象列表分组为5分钟,最好使用流和收集器。



我在StackOverflow上找到的唯一可行解决方案是计算我需要多少个间隔(子列表),将每个对象添加到这些列表中的每一个,并过滤掉那些不适合相应时间范围的对象,这不是一个很好的解决方案。



(你可以在这里找到线程:如何按Java 8中的另一个元素对List的元素进行分组



我想到类似的东西:

  List< MyObject> list = new ArrayList< MyObject>(); 
.......
列表< List< MyObject>> grouped = list.stream()。collect(Collectors.groupingBy(obj - > obj.getTime()/ intervalLength));

这当然是最好的工作。



我希望,Java 8&它的功能越来越多,我们可以为这样的问题找到一个suting解决方案。



问候,
Claas M。



编辑:
最后,我使用了@Harsh Poddar的解决方案并使用



<$ p $将地图转换为列表列表p> for(Map.Entry< Integer,List< MyObject>> entry:map.entrySet())
list.add(entry.getValue());

注意:之后必须对List进行排序。

解决方案

这完全正常:

  Map< Long,< List< ;为MyObject>> grouped = ticks.stream()。collect(Collectors.groupingBy(obj  - > obj.getTime()/ intervalLength)); 

此方法将为您提供一个地图,您可以在该地图上调用.values()来获取列表列表第一个元素将包含obj.getTime()从0到intervalLength的元素,只要有这样的元素。第二个将包含intervalLength到intervalLength * 2,依此类推


I want to group a List of Objects containing a time attribute into 5-Minute intervals, preferably using streams and collectors.

The only possible solution I found on StackOverflow is to calculate how many intervals (sublists) I need, add every object to every one of these Lists and filter out the ones that dont fit into the respective timeframe, which is not exactly a nice solution.

(You can find the Thread here: How to group elements of a List by elements of another in Java 8)

I thought of something similar to this:

List<MyObject> list = new ArrayList<MyObject>();
.......
List<List<MyObject>> grouped = list.stream().collect(Collectors.groupingBy(obj -> obj.getTime() / intervalLength));

This of course doenst work.

I hope that, with Java 8 & its features being used more and more, we can find a suting solution for such a Problem.

Regards, Claas M.

EDIT: In the End, I used @Harsh Poddar's solution and converted the Map into a List of Lists using

for(Map.Entry<Integer, List<MyObject>> entry:map.entrySet())
  list.add(entry.getValue());

Note: The List had to be sorted afterwards.

解决方案

This works totally fine:

Map<Long,<List<MyObject>> grouped = ticks.stream().collect(Collectors.groupingBy(obj -> obj.getTime() / intervalLength));

This method will give you a map on which you may then call .values() to get the list of lists. First element will contain elements with obj.getTime() from 0 to intervalLength provided there were such elements. The second will contain from intervalLength to intervalLength*2 and so on

这篇关于如何使用流和&amp ;;将列表中的对象按属性分组到其他列表中Java 8?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆