java如何使用stream对两个list进行操作

两个list数组,list1[1,1,null,1,null,1,1],list2[a,b,c,d,e,f,g]。当list1里的值为null时,去掉对应的list2里面的同样下标位置的值。

    list2.stream().map(l2 -> {
        list1.stream().filter(l1 -> {
            //这里该怎么写?
        })
    }).collect(Collectors.toList());

第二层流操作该怎么写才能筛出我想要的结果

阅读 5.6k
2 个回答

Java Stream 迭代过程不带下标,真不好耍,还好这个问题可以稍微换下思路

public class Q1010000040707997 {
    public static void main(String[] args) {
        List<Integer> l1 = Arrays.asList(1, 1, null, 1, null, 1, 1);
        List<String> l2 = Arrays.asList("a", "b", "c", "d", "e", "f", "g");

        List<String> result = IntStream.range(0, l1.size())
            .filter(i -> l1.get(i) != null)
            .mapToObj(i -> l2.get(i))
            .collect(Collectors.toList());

        System.out.println(result);
    }
}

顺便看下,带下标的 JavaScript 写法

const l1 = [1, 1, null, 1, null, 1, 1];
const l2 = ["a", "b", "c", "d", "e", "f", "g"];

const result = l2.filter((_, i) => l1[i] !== null);

console.log(result);

在意下标的逻辑,就用下标操作

public class Sf1010000040707997 {

    public static void main(String[] args) {
        List<Integer> l1 = Arrays.asList(1, 1, null, 1, null, 1, 1);
        List<String> l2 = Arrays.asList("a", "b", "c", "d", "e", "f", "g");

        List<String> collect = IntStream.range(0, l1.size())
                .mapToObj(i -> {
                    Integer i1 = l1.get(i);
                    if (i1 != null) {
                        return l2.get(i);
                    } else {
                        return null;
                    }
                }).collect(Collectors.toList());

        System.out.println(collect);
    }
}
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题