使用Java 8流(Stream)比较两个列表中相同位置的元素。

huangapple go评论78阅读模式
英文:

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&lt;Integer&gt; list1 = List.of(99, 22, 33);
List&lt;Integer&gt; list2 = List.of(11, 24, 33);

// safeguard against different sized lists.
int minLen = Math.min(list1.size(), list2.size());
List&lt;Integer&gt; result = IntStream.range(0, minLen)
		.map(i -&gt; list1.get(i).compareTo(list2.get(i)))
		.boxed().collect(Collectors.toList());

System.out.println(result);

Prints

[1, -1, 0]

</details>



huangapple
  • 本文由 发表于 2020年4月5日 05:17:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/61034917.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定