php小编鱼仔为您带来本期java问答,探讨java中如何使用流式传输处理数组列表,并与先前的记录进行比较。通过本文,您将了解如何利用java的流式处理功能,高效地对数组列表进行操作,并实现与之前记录的比较。让我们一起深入探讨这一主题,提升对java编程的理解与技能水平。
我有一个简单的 recorda 类,它包含一个 id 和一个 int 值。多个“已排序”recorda 元素存储在列表中。
我想遍历列表并将当前元素与前一个元素进行比较,并找到它们值的差异。
代码:
import java.util.*;
class RecordA{
Integer id;
Integer value;
RecordA(Integer id, Integer value) {
this.id = id;
this.value = value;
}
Integer getId() { return id;}
Integer getValue() { return value;}
}
class RecordB {
Integer id;
Integer value;
Integer diff;
RecordB(Integer id, Integer value, Integer diff) {
this.id = id;
this.value = value;
this.diff = diff;
}
Integer getId() { return id;}
Integer getValue() { return value;}
Integer getDiff() { return diff;}
}
class HelloWorld {
public static void main(String[] args) {
List<RecordA> listA = new ArrayList<>();
RecordA recordA1 = new RecordA(1,10);
listA.add(recordA1);
RecordA recordA2 = new RecordA(2,15);
listA.add(recordA2);
RecordA recordA3 = new RecordA(3,25);
listA.add(recordA3);
RecordA recordA4 = new RecordA(4,30);
listA.add(recordA4);
System.out.println(listA.size());
}
}我想使用流(如果可能)将当前 recorda.value 与先前的 recorda.value 进行比较,将结果映射到具有相同 id 和值的 recordb 中,但存储当前-上一个。
立即学习“Java免费学习笔记(深入)”;
最后,recordb 列表将包含
我想避免类 for 循环和 previous_val 变量。有什么想法如何使用流来做到这一点吗?
您可以使用 intstream
intstream.range(0, lista.size())
.map(index ->
new recordb(lista.get(index).getid(), lista.get(index).getvalue(), lista.get(index).getvalue() - (index > 0 ? lista.get(index - 1).getvalue() : 0))
)
.collect(collectors.tolist())这是一种有点不直观的方法,我实际上必须查一下。
StackOverflow – Java Stream Using Previous Element in Foreach Lambda。
通常,流的使用是聚合一组值,而不一定是比较和对比它们。
Lesson: Aggregate Operations (The Java™ Tutorials > Collections)。
这是一个使用 Collector 类和 Collector#of 方法的示例。
本质上,在收集过程中,您可以从已收集的内容中检索前一个元素。
对于 BiConsumer 参数,a 是迄今为止收集的元素。
list<recordb> l
= lista.stream()
.collect(
collector.<recorda, list<recordb>, list<recordb>>of(
arraylist::new,
(a, b) -> {
if (a.isempty()) a.add(new recordb(b.id, b.value, 0));
else {
recordb x = a.get(a.size() - 1);
a.add(new recordb(b.id, b.value, b.value - x.value));
}
},
(a, b) -> {
a.addall(b);
return a;
},
x -> x));
输出
1, 10, 0 2, 15, 5 3, 25, 10 4, 30, 5
最后一点,您可能希望摆脱 recordb 类,而只使用 Map。
Map<RecordA, Integer> m = new LinkedHashMap<>();
RecordA a, b;
m.put(a = listA.get(0), 0);
for (int i = 1, n = listA.size(); i < n; i++)
m.put(b = listA.get(i), -a.value + (a = b).value);
以上就是Java流式传输数组列表并与先前的记录进行比较的详细内容,更多请关注php中文网其它相关文章!
java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号