【问题标题】:Compare two Collections populated with different kinds of objects比较两个填充了不同类型对象的集合
【发布时间】:2021-10-08 18:54:54
【问题描述】:

我在尝试比较两个大型集合时遇到性能问题,我正在寻求帮助以找到更好的方法。

课程:

public class TypeOne {
   private int id;
}

public class TypeTwo {
   private int id;
}

代码:

Collection<TypeOne> oneColl = someMethodToPopulateThat();
Collection<TypeTwo> twoColl = anotherMethodToPopulateThat();

// Iterating both collections to match the elements by id
for(TypeOne one : oneColl) {
   for(TypeTwo two : twoColl) {
      if (one.getId().equals(two.getId())) 
         System.out.println(one.getId());
   }
}

我已经尝试使用 Stream API 的一些功能,但没有成功。 有没有人有任何想法来解决这个问题?请。

提前致谢。

【问题讨论】:

    标签: java collections stream


    【解决方案1】:

    tl;博士

    ones.stream().forEach(
        one -> System.out.println(
            twos.stream().filter( two -> two.getId() == one.getId() ).findAny().toString()
        )
    )
    

    详情

    我认为排序为NavigableSet 会提高我们的搜索性能,尽管我尚未验证这种优化尝试是否有效。

    NavigableSet < TypeOne > ones = new TreeSet <>( Comparator.comparingInt( TypeOne :: getId ) );
    ones.addAll( collectionOfOnes ) ;
    
    NavigableSet < TypeTwo > twos = new TreeSet <>( Comparator.comparingInt( TypeTwo :: getId ) );
    twos.addAll( collectionOfTwos ) ;
    

    循环一个可导航集,同时在另一个中搜索匹配项。

    for( TypeOne one : ones )
    {
        Optional<TypeTwo> optionalTwo = twos.stream().filter( two -> two.getId() == one.getId() ).findAny() ;
        // handle your Optional which may or may not contain an object. 
    }
    

    【讨论】:

      猜你喜欢
      • 2019-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-08
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多