gpt4 book ai didi

java - 根据自定义数据过滤列表

转载 作者:行者123 更新时间:2023-12-02 12:50:58 25 4
gpt4 key购买 nike

我有课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 条记录。

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

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

最佳答案

如果您希望列表很短,您可以直接强力搜索所有累积组合。以下代码片段使用 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();

关于java - 根据自定义数据过滤列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44611775/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com