【问题标题】:How to compare lists of different types如何比较不同类型的列表
【发布时间】:2019-06-19 13:52:50
【问题描述】:

我有两个列表。一个列表有 6 个元素,另一个列表有 3 个元素。我需要比较两个列表并仅保留与 bList 匹配的 aList 中的信息。

public class AClass{

    String cname;
    int cid;
    int aid;
}

public class BClass{
    String cname;
    int sc_id;
    int aid;
}

还有两个列表:

List<AClass> aList;
List<BClass> bList;

例如,aList 有 1,2,3,4,5,6,bList 有 1,4,5。必须进行比较,以便 aList 中有 1,4,5。

我试过下面的代码。但不起作用。

aList.retainAll(bList);

请帮忙!

【问题讨论】:

  • 你想比较什么?
  • 您是否尝试将bList 中的所有对象映射到AClass 对象?然后将 aList 与您创建的这个新列表进行比较。
  • 当您说aList has 1,2,3,4,5,6 时,您到底是什么意思?因为您的类不仅仅包含一个整数。
  • @OHGODSPIDERS aList 1,2,3,4,5,6 指的是 cid。两个列表都有一个共同的字段。 aList 的 cid 与 bList 的 sc_id 相同
  • @MuratKaragöz 我想比较两个列表中的 ids(aList 的 cid 和 bList 的 sc_id),并只保留匹配的信息。

标签: java arraylist collections hashmap


【解决方案1】:

基本上,这个想法是将aList 的每个元素与bList 的每个元素进行比较,同时比较sc_id == e.cid。您可以为此使用流。看起来像这样

aList = aList.stream().filter(e -> bList.stream().anyMatch(b -> b.sc_id == e.cid)).collect(Collectors.toList());

【讨论】:

    【解决方案2】:

    先获取要保留的 id,然后过滤它们。

    Set<Integer> keepIds = bList.stream().map(BClass:getId).collect(toSet());
    List<AClass> filtered = aList.stream
                                 .filter(a -> keepIds.contains(a.getId()))
                                 .collect(toList());
    

    【讨论】:

      【解决方案3】:
      List<Integer> a = List.of(1,2,3,4,5);
      List<Integer> b = List.of(1,4,6);
      List<Integer> collect = a.stream().filter(b::contains).collect(Collectors.toList());
      System.out.println(collect);
      

      【讨论】:

      • 他没有整数列表。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-19
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 2022-06-16
      • 1970-01-01
      相关资源
      最近更新 更多