我有一个包含相当多字段的列表,需要使用流一次性创建一个列表。
我们需要将 List 中的字段标记为 current true,以获取输入 List 中的最小正整数
输入:
[PT(pn=-1, endDate=2019-01-11, dp=MAR 2019,..), PT(pn=4, endDate=null, dp=APR 2019,..), PT(pn=6, endDate=2019-05-11, dp=MAY 2019,..)]
输出:
[OP(pn=11, current=false, dp=MAR 2019), OP(pn=4, current=true, dp=APR 2019), OP(pn=6, current=false, dp=MAY 2019)]
class OP{
Integer pn;
Boolean current;
String dp;
}
List<OP> filteredList11 = availablePT.get()
.stream()
.map(e->new OP(e.getPn(),**,e.getDp()))
.collect(Collectors.toList());
我有点困惑如何导出逻辑以将当前标志(**)更新为单个循环中最小正整数的 true。
最佳答案
这是另一种方法。 有一个 OP 构造函数,它接受 PT 并映射所有字段,加上默认设置为 false 的额外 boolean 值。
然后做这样的事情:
List<OP> ops = availablePT.stream().map(dp -> {return new OP(dp);})
.filter(line -> line.getPn()!=null && line.getPn().doubleValue()>=0)
.sorted(Comparator.comparingInt(OP::getPn))
.collect(Collectors.toList());
if(ops!=null && !ops.isEmpty()) {
ops.get(0).setCurrent(true);
}
这基本上创建了新对象,然后过滤掉负数,然后对正数进行排序,然后保证具有最小 dp 值的操作是第一个,因此将其 boolean 值设置为 true
关于Java流: Difficulty in object property update,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59621632/