英文:
Comparing elements at same position of two list using Java 8 stream
问题
我有两个列表,我想要比较列表1的每个元素与列表2,并将结果放入列表3,例如
List1 = {99,22,33}
list2 = {11,24,33}
结果:
list3 = {1,-1,0}
我如何做到这一点,最好使用流?
英文:
I have two lists I want to compare each element of list 1 to list 2 and get result in list 3 e.g
List1 = {99,22,33}
list2 = {11,24,33}
Result:
list3 = {1,-1,0}
How I can do this preferably using stream?
答案1
得分: 5
尝试这样写:
这将用比较的结果替换用于索引每个列表的ints
流。然后将这些结果收集到一个列表中。
注意:我添加了一个保护措施来处理不同大小的列表。它将使用两者中较小的一个,以防止抛出异常。但较长列表的尾部元素将被忽略。
List<Integer> list1 = List.of(99, 22, 33);
List<Integer> list2 = List.of(11, 24, 33);
// 防止不同大小的列表。
int minLen = Math.min(list1.size(), list2.size());
List<Integer> result = IntStream.range(0, minLen)
.map(i -> list1.get(i).compareTo(list2.get(i)))
.boxed().collect(Collectors.toList());
System.out.println(result);
输出
[1, -1, 0]
英文:
Try it like this:
This replaces the stream of ints
used to index each list, with the result of the comparison. Then collect those into a list.
Note: I added a safeguard to account for different size lists. It will use the smaller of the two to prevent an exception being thrown. But trailing elements of the longer list will be ignored.
List<Integer> list1 = List.of(99, 22, 33);
List<Integer> list2 = List.of(11, 24, 33);
// safeguard against different sized lists.
int minLen = Math.min(list1.size(), list2.size());
List<Integer> result = IntStream.range(0, minLen)
.map(i -> list1.get(i).compareTo(list2.get(i)))
.boxed().collect(Collectors.toList());
System.out.println(result);
Prints
[1, -1, 0]
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论