【问题标题】:How to "remove all duplicates and original of duplicate" from a list of objects in Java 8?如何从 Java 8 中的对象列表中“删除所有重复项和重复项的原始项”?
【发布时间】:2021-01-24 12:23:20
【问题描述】:

我有两个:

registryId:1
registryID:1
registryID:2

最终列表应该是:我的意思是完全删除 1

registryID:2

我得到了这个解决方案:

List<TerpAccountListV> terpAccountListVFinal = compareUpdate(terpAccountListV, xxedgeAccountsListV);

Set<TerpAccountListV> set = terpAccountListVFinal.stream()
                    .collect(Collectors.toCollection(() -> new TreeSet()<>(Comparator.comparing(TerpAccountListV::getRegistryId))));

但是这会使 Single Set 具有注册表 ID。

如何在 Java 8 中使用这个集合从上面的列表中删除元素?

【问题讨论】:

  • .stream().distinct() 呢?
  • @VLAZ:不,它保留原始元素,就像在示例中我解释说我只需要 2 但应该完全使用 1。更新问题

标签: list lambda java-8 set comparator


【解决方案1】:

首先,在列表中按RegistryId 计数出现次数。然后创建一组非重复项的RegistryId

Set<Integer> set = 
        list.stream()
            .collect(Collectors.groupingBy(TerpAccountListV::getRegistryId,
                                           Collectors.counting()))
            .entrySet().stream()
            .filter(e -> e.getValue() == 1L)
            .map(e -> e.getKey())
            .collect(Collector.toSet());

如果RegistryId包含在集合中,则过滤列表

List<TerpAccountListV> res =  list.stream()
                                  .filter(e -> set.contains(e.getRegistryId()))
                                  .collect(Collector.toList());

更新: 您也可以通过这种方式进行设置创建部分

Set<Integer> track = new HashSet<>();
Set<Integer> set = new HashSet<>();
for (Integer item : list) {
  if(!track.add(item.getRegistryId())) {
    set.remove(item.getRegistryId());
  } else {
    set.add(item.getRegistryId());
  }
}

【讨论】:

  • 对于 10^5,我认为它的工作很好,虽然我添加了一种使用两个集合创建集合的迭代方法。
猜你喜欢
  • 1970-01-01
  • 2015-01-03
  • 2013-05-11
  • 2019-08-04
  • 1970-01-01
  • 2011-10-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多