How to Group Objects in a List into other Lists by Attribute using streams & Java 8?

孤街浪徒 提交于 2019-12-04 09:47:56

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

Use a function to map a time to a bucket:

// assume time is in seconds
int bucketNumber(int baseTime, int thisTime) {
    return (thisTime - baseTime) / 300;
}

Then collect by bucket number:

ticks.stream().collect(groupingBy(e -> bucketNumber(baseTime, e.getTime()));

Now you have a Map<Integer, List<Tick>> where the key is the index of the five-minute bucket starting at baseTime, and a list of ticks in that bucket. If you just want a histogram, use a downstream collector:

ticks.stream().collect(groupingBy(e -> bucketNumber(baseTime, e.getTime()), 
                                  counting());
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!