gpt4 book ai didi

Java从ArrayList中删除重复出现的对象并使其唯一

转载 作者:行者123 更新时间:2023-11-29 06:53:03 26 4
gpt4 key购买 nike

ArrayList 有问题。我正在用以下方法填充 Arraylist。

private void fillData() {
mArrayList = new ArrayList<>();
DemoTestBean bean = new DemoTestBean();
bean.id = "1";
bean.name = "Test1";
bean.percentage = 20;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "1";
bean.name = "Test2";
bean.percentage = 30;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "1";
bean.name = "Test3";
bean.percentage = 50;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "2";
bean.name = "Test4";
bean.percentage = 40;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "4";
bean.name = "Test5";
bean.percentage = 55;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "5";
bean.name = "Test6";
bean.percentage = 25;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "6";
bean.name = "Test7";
bean.percentage = 60;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "6";
bean.name = "Test8";
bean.percentage = 40;
mArrayList.add(bean);
}

现在我只想添加一次重复对象。但是当我发现重复的 id 时,我需要将百分比值的总和合并为一个。所以新数组将如下所示:

private void fillData() {
mArrayList = new ArrayList<>();
DemoTestBean bean = new DemoTestBean();
bean.id = "1";
bean.name = "Test1";
bean.percentage = 100;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "2";
bean.name = "Test2";
bean.percentage = 40;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "4";
bean.name = "Test3";
bean.percentage = 55;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "5";
bean.name = "Test4";
bean.percentage = 25;
mArrayList.add(bean);

bean = new DemoTestBean();
bean.id = "6";
bean.name = "Test5";
bean.percentage = 100;
mArrayList.add(bean);
}

这意味着我们有 3 个具有 id 1 的重复对象,在新数组中我们需要将具有相同 id 的所有百分比值相加并将其视为一个对象。所以我们的新数组列表是这样构建的。但我不知道如何解决这个问题。请帮助我。

最佳答案

最简单的方法是将 List 转换为支持唯一性的不同 Collection 类型。这是 Set 的任何实现

关于Java从ArrayList中删除重复出现的对象并使其唯一,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41301518/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com