【问题标题】:Retain all values with multiple lists使用多个列表保留所有值
【发布时间】:2021-01-30 04:00:23
【问题描述】:

在java中,我有List<Integer> source, list1, list2。 所以,我必须保留sourcelist1list2 之类的

// #source = {1, 2, 3, 4, 5}, #list1 = {1, 2}, #list2={3}

source.retainAll(list1, list2);

// New source should like #source = {1, 2, 3}

但是retainAll 只接受一个参数,但我们必须传递多个参数。 有办法吗?

【问题讨论】:

    标签: java list collections set


    【解决方案1】:

    方法retainAll 没有带有两个参数的重新加载版本。您可以使用 API Collection 的接口(方法Collection.addAll)来合并两个列表,例如:

    List<Integer> source = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
    List<Integer> list1 = new ArrayList<>(Arrays.asList(1, 2));
    List<Integer> list2 = Arrays.asList(3);
    list1.addAll(list2);
    
    source.retainAll(list1);
    
    System.out.println(source);
    

    输出:

    [1, 2, 3]
    

    【讨论】:

      【解决方案2】:

      您可以将两个列表展平为一个set,然后使用retainAll 方法,或者改用filter 方法:

      List<Integer> source = new ArrayList<>(List.of(1, 2, 3, 4, 5));
      List<Integer> list1 = List.of(1, 2);
      List<Integer> list2 = List.of(3);
      
      source.retainAll(Stream.of(list1, list2)
              .flatMap(List::stream)
              .collect(Collectors.toSet()));
      
      System.out.println(source); // [1, 2, 3]
      
      List<Integer> target = source.stream()
              .filter(e -> list1.contains(e) || list2.contains(e))
              .collect(Collectors.toList());
      
      System.out.println(target); // [1, 2, 3]
      

      【讨论】:

        【解决方案3】:

        您可以在retainAll() 中使用 var args 作为参数。

        您可以调用retainAll(),提供任意数量的参数。

        喜欢,

        source.retainAll(list1, list2, list3);
        
        private void retainAll(List<Integer>... lists){
            // you logic goes here
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-02-14
          • 2016-12-10
          • 1970-01-01
          • 2022-11-15
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多