添加在ArrayList中重复元素的值 [英] Adding values of repeated elements in ArrayList

查看:360
本文介绍了添加在ArrayList中重复元素的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个的ArrayList 记录。

package com.demo.myproject;

public class Records 
{
    String countryName;
    long numberOfDays;

    public String getCountryName() {
        return countryName;
    }
    public void setCountryName(String countryName) {
        this.countryName = countryName;
    }
    public long getNumberOfDays() {
        return numberOfDays;
    }
    public void setNumberOfDays(long numberOfDays) {
        this.numberOfDays = numberOfDays;
    }

    Records(long days,String cName)
    {
        numberOfDays=days;
        countryName=cName;
    }
}

我的的ArrayList<唱片和GT; 是包含值

 Singapore     12 
 Canada         3
 United Sates  12
 Singapore     21

我需要修改它,这样我的输出是

I need to modify it such that my output is

Canada         3
Singapore     33
United States 12

请帮我解决,方法。

推荐答案

您可以在你的记录存储在一个地图,其中关键的是全国各地。

You could store your Records in a Map, where the key would be the country.

当您收到一个新的记录,检查是否在全国已是地图,如果是,增加的天数,如果不创建它。

When you receive a new Record, check if the country already is in the map, if it is, add the number of days, if not create it.

Map<String, Record> map = new HashMap<String, Record> ();

addRecord(map, someRecord);

private void addRecord(Map<String, Record> map, Record record) {
    Record inMap = map.get(record.getCountryName());
    if (inMap == null) {
        inMap = record;
    } else {
        inMap.setNumberOfDays(inMap.getNumberOfDays() + record.getNumberOfDays());
    }
    map.put(record.getCountryName(), inMap);
}

注:


  • 我认为它是好的修改记录 - 如果不只是创建一个使用天的总和一个新的

  • 您仍然可以通过调用获得的记录集 map.values​​(); 并在它们之间迭代

  • ArrayList是不是很适合你的使用情况。如果你真的要坚持ArrayList中,对伊芙新的记录,您将需要遍历列表,检查列表中的一个记录有相同的国家作为新的记录,如果你觉得它更新的记录,或添加一个新的记录,如果没有。

  • I have assumed that it is fine to modify the records - if not just create a new one using the sum of the days.
  • you can still get the collection of records by calling map.values(); and iterate over them
  • ArrayList is not very well suited for your use case. If you really need to stick to ArrayList, for evey new record, you would need to loop over the list, check if one of the records in the list has the same country as the new record, update that record if you find it, or add a new record if not.

这篇关于添加在ArrayList中重复元素的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆