2017-06-18 135 views
0

我有一个类Accumulation像下面过滤列表

public class Accumulation implements Serializable { 
    private static final long serialVersionUID = 1L; 

    private String mobileNo; 
    private String address; 
    private int count; 

    -- 
    getter 
    setter 
} 

我通过

List<Accumulation> accumulations = repository.getAccumulation(); 

从我的存储库中获得数据现在为例List<Accumulation>积累包含5个记录。

First records : 123, Test1, 2 
Second records : 123, Test1, 2 
Third records : 123, Test1, 2 
Fourth records : 123, Test1, 1 
Fifth records : 123, Test1, 2 

我们可以通过下面的代码得到总数。

int totalCount = accumulations.stream().mapToInt(Accumulation::getCount).sum(); 

因此,从上述列表中,我们可以得到总数为:: 9

什么,我想:我想只得到8计数的记录。

例如:如果我们只得到4条记录(第一,第二,第三,第五条),那么我们可以得到8个计数。

如何实现上述逻辑?我找不到任何东西。

+0

你试图让,使计8种元素的子表? (如果我理解正确)。你应该清楚地解决它。 –

+0

@ShafinMahmud正确 –

+0

你的目标是什么?获取没有最后一个元素的列表或根据指定记录计数获取列表? – ledniov

回答

1

如果你期待的名单要短,你可以brute-强制搜索累积的所有组合。下面的代码片段利用BitSet类的避免做人工操纵掩码:

import static java.util.stream.Collectors.toList; 

Optional<List<Accumulation>> result = LongStream.range(0, 1L << accumulations.size()) 
    .mapToObj(bits -> BitSet.valueOf(new long[] {bits})) 
    .filter(bits -> 8 == bits.stream() 
      .map(i -> accumulations.get(i).getCount()) 
      .sum() 
    ) 
    .map(bits -> bits.stream() 
      .mapToObj(accumulations::get) 
      .collect(toList()) 
    ) 
    .findFirst(); 
0

如果你想要得到的返回列表的子可以用List.subList

为了得到8个元素:

ListItems.subList(0, 8); 
+1

我认为他没有要求8个元素。他要求提供计数的元素子列表8.所以这不是正确答案 –

+0

@ShafinMahmud Correct –