【问题标题】:read the elements and add the unique elements in other object读取元素并在其他对象中添加唯一元素
【发布时间】:2022-01-05 18:35:21
【问题描述】:

我有以下示例代码。

 List<MyItemsData.GroupItemInfo> itemsList = new ArrayList<>();
    //some business logic to add the MyItemsData objects in the itemsList.
    itemsList.stream().forEach(groupItemInfo -> {
                if (groupItemInfo.getItems().isEmpty()) {
                    System.out.println("item is null");
                } else {
                    System.out.println("item not null " + groupItemInfo.getItems().size());
                }
                if (!groupItemInfo.getItems().isEmpty()) {
    
                }
            });

我想存储 type!=null 并且应该是唯一的所有对象的所有项目(不允许重复)

【问题讨论】:

  • 最初的值在哪里?您的调试屏幕截图中显示了什么变量?

标签: java java-8


【解决方案1】:

只保留items 不为空的元素,从您的代码中进行最少的修改

List<MyItemsData> result = ...; // initial data
List<MyItemsData> itemWithNotEmptyItems = new ArrayList<>();

result.forEach(groupItemInfo -> {
    if (!groupItemInfo.getItems().isEmpty()) {
        itemWithNotEmptyItems.add(groupItemInfo);
    }
});

使用Stream,您可以过滤result,然后收集到一个列表

List<MyItemsData> result = new ArrayList<>();
List<MyItemsData> itemWithNotEmptyItems = result.stream()
        .filter(groupItemInfo -> !groupItemInfo.getItems().isEmpty())
        .collect(Collectors.toList());

【讨论】:

  • 我按照您的建议尝试了上面的代码,但它没有添加来自其他对象的元素,这些对象的类型!= null 在第一个类型为 null 的对象中。相反,它没有在列表中显示 type=null 值的对象,如编辑部分中添加的图像所示。 @azro
【解决方案2】:

如下修改您的 MyItemsData,

  1. 实现相等和哈希码,只比较类型,因为唯一性取决于类型。
  2. 实现方法以返回 MyItemsData 的布尔状态(如果类型为 null 或项目为空,则返回 false”

MyItemsData 类示例:

public static final class MyItemsData {
        private String type;
        private List items;

        public String getType() {
            return type;
        }

        public List getItems() {
            return items;
        }

        public boolean isValid() {
            return null != type && !type.isEmpty() && null != items && !items.isEmpty();
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }
            if (o == null || getClass() != o.getClass()) {
                return false;
            }

            MyItemsData that = (MyItemsData) o;

            return type != null ? type.equals(that.type) : that.type == null;
        }

        @Override
        public int hashCode() {
            return type != null ? type.hashCode() : 0;
        }
    }
 

然后您可以使用流过滤并获取不同的数据作为列表。

代码:

List<MyItemsData> result = source.stream().filter(MyItemsData::isValid).distinct().collect(Collectors.toList());

【讨论】:

  • 我想尝试不覆盖equals和hashcode,因为我只有服务逻辑和我不应该更改的模型类。 @Chamly Idunil
【解决方案3】:

让我们定义一个类(以明确我们的工作):

public class MyItemsData {

    public static class GroupItemInfo {

        private String type;
        private List<Item> items;

        public String getType() {
            return type;
        }

        public List<Item> getItems() {
            return items;
        }

        public static class Item {}

    }

}

然后您可以为MyItemsData.GroupItemInfo.Item 定义自定义比较器。然后使用Stream,您可以创建TreeSet 以使用给定的比较器检索唯一项目。然后你可以建立一个List

public static void main(String... args) {
    List<MyItemsData.GroupItemInfo> itemsList = new ArrayList<>();
    List<MyItemsData.GroupItemInfo.Item> uniqueItems = getUniqueItems(itemsList);
}

public static List<MyItemsData.GroupItemInfo.Item> getUniqueItems(List<MyItemsData.GroupItemInfo> items) {
    final Comparator<MyItemsData.GroupItemInfo.Item> comparator = (one, two) -> {
        // TODO implement comparator (return =0 for equal items)
        return 0;
    };

    return new ArrayList<>(items.stream()
                                .filter(item -> item.getType() != null)
                                .filter(item -> !item.getItems().isEmpty())
                                .map(MyItemsData.GroupItemInfo::getItems)
                                .flatMap(List::stream)
                                .collect(Collectors.toCollection(() -> new TreeSet<>(comparator))));
}

【讨论】:

  • 请参阅上面的帖子编辑并添加整个 java 类以更清晰
猜你喜欢
  • 2011-03-24
  • 2019-09-04
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多