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

时间:2016-12-23 12:26:43

标签: java android sorting arraylist collections

我遇到了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的所有百分比值相加并将其视为一个对象。所以我们新的arraylist就像这样构建。 但我不知道怎么能弄清楚这个问题。请帮帮我。

2 个答案:

答案 0 :(得分:3)

最简单的方法是将List转换为支持唯一性的其他Collection类型。这是Set

的任何实现

答案 1 :(得分:3)

您可以执行以下操作:

public void add(DemoTestBean testBean)
{
    DemoTestBean bean = find(list,testBean.getId());
    if(bean!=null)
         bean.setPercentage(bean.getPercentage()+testBean.getPercentage());
    else
         list.add(testBean);
}
public DemoTestBean find(List<DemoTestBean> list, int id)
{
    for(DemoTestBean bean:list)
    {
        if(bean.getId() == id)
            return bean;
    }
    return null;
}

我将find的实施留给您。