【问题标题】:Compare two different type of ArrayLists to find common data比较两种不同类型的 ArrayList 以找到共同的数据
【发布时间】:2015-01-13 16:06:52
【问题描述】:

我有两个 ArrayList。 Arraylist one 存储包含不同属性的对象,其中一个是整数数组列表。

Arraylist 2 是一个整数数组列表。我想将 Arraylist 2 与存储在 Arraylist 1 中的整数数组列表进行比较。为了让您更容易理解:

数组列表1:

  • 属性 1
  • 属性 2
  • 整数数组列表

ArrayList2/整数数组列表

我已经尝试了几个小时来做​​到这一点,但没有成功。这是我的想法:

我有这两个 ArrayList:

ArrayList<LottoTicket> ticketList = new ArrayList<>(); //ArrayList 1

ArrayList<Integer> drawNums = new ArrayList(); //ArrayList 2

现在 ArrayList 1 存储 LotteryTicket 对象,该对象有一个名为“set”的整数 ArrayList,其中存储 5 个彩票号码。

这是我将“set”数组列表与 drawNums 数组列表进行比较的想法:

for(LottoTicket l : ticketList)
{        
  if(l.getSet().contains(drawNums.get(1)))
  {
     System.out.println("1 number matches");
  } 
  else 
  {
     System.out.println("No matches");
  }
}

但这似乎不是一个好主意!任何帮助将不胜感激,我希望这对其他人也有帮助!

谢谢

【问题讨论】:

    标签: java arraylist collections compare


    【解决方案1】:

    我认为您正在寻找两个Collection(s) 的共同项目。你可以List.retainAll(Collection) 从这个列表中删除所有不包含在指定集合中的元素 和类似的东西,

    List<Integer> al = new ArrayList<>(l.getSet());
    al.retainAll(drawNums);
    System.out.printf("%d number(s) match.%n", al.size());
    

    【讨论】:

    • 感谢您的回复!但这是否需要在我引用 ArrayList 中的每张票的 foreach 循环中?
    • 是的,为了打电话给l.getSet()
    • 感谢您的帮助!
    【解决方案2】:

    您应该只检查列表contains玩家选择的号码,而不是检查抽奖号码列表中的特定位置——毕竟,号码的顺序不应该事情。然后,只需 count 包含的数字。

    此外,您可以将 Lists 转换为 Sets 以加快查找速度(尽管这对于只有五个数字应该无关紧要)。

    Set<Integer> numsAsSet = new HashSet<>(drawNums);
    for (LottoTicket ticket : ticketList) {
        long matches = ticket.getSet().stream()
                                      .filter(x -> numsAsSet.contains(x))
                                      .count();
        System.out.println("Number of matches: " + matches);
    }
    

    【讨论】:

      猜你喜欢
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 2022-11-18
      • 2019-08-06
      • 2014-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多