如何使用流从两个列表或数组乘法中查找元素对 [英] How to use streams to find pairs of elements from two lists or array multiplication

查看:53
本文介绍了如何使用流从两个列表或数组乘法中查找元素对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数字列表,我想找到所有可能的数字对.例如,给定列表 [1、2、3] [3、4] ,结果应为:

I have two lists of numbers and I'd like to find all possible pairs of numbers. For example, given the lists [1, 2, 3] and [3, 4] the result should be:

[(1, 3), (1, 4), (2, 3), (2, 4), (3, 3), (3, 4)]

我知道我可以使用 for循环来做到这一点,但是还有其他更简洁的方法可以使用 Java 8流吗?

I know I can do this using a for loop but is there any more concise way to do it using Java 8 streams?

我尝试了以下操作,但由于缺少 List< int []> .

I tried the following, but I'm missing something as I'm getting List<Stream<int[]>> instead of List<int[]>.

public static void main(String[] args) {
    List<Integer> list1 = Arrays.asList(1, 2, 3);
    List<Integer> list2 = Arrays.asList(3, 4);
    List<int[]> pairs = list1.stream()
                             .map(i -> list2.stream()
                                            .map(j -> new int[]{i, j}))
                             .collect(Collectors.toList());
    pairs.forEach(i -> {
        System.out.println("{" + i[0] + "," + i[1] + "}");
    });
}

推荐答案

使用 flatMap()方法代替 map()方法,它将流合并为一个.请参阅: map()和flatMap()

Use flatMap() method instead of map(), it will combine the streams into one. Refer : Difference Between map() and flatMap() and flatMap() example

这篇关于如何使用流从两个列表或数组乘法中查找元素对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆