简体   繁体   中英

How to implement java code using collections for below requirement?

I have three fields: Material, Date, Quantity

Material     Date             quantity 
   96111     05/06/2020       5 
   96111     05/06/2020       2 
   96111     05/06/2020       4 
   96112     06/06/2020       3 
   96113     06/07/2020       1

For one date there will be duplicate material numbers, we need to skip duplicate date and material, send only one date with material by adding quantity.

output:

Material         Date           Quantity
96111           05/06/2020         11
96112           06/06/2020          3
96113           06/07/2020          1

Assuming every date has only one material sold.

import java.util.*;
class object_{
    long material;
    String date;
    int quantity;
    object_(long m,String date,int quantity){
        material = m;
        this.date = date;
        this.quantity = quantity;
    }
    @Override
    public String toString(){
        return "o(material:"+material+" date:"+date+" quantity:"+quantity+")";
    }
}
public class Main
{
    public static void main(String[] args) {
        object_ objs[]=new object_[5];
        objs[0]=new object_(96111,"05/06/2020",5);
        objs[1]=new object_(96111,"05/06/2020",2);
        objs[2]=new object_(96111,"05/06/2020",4);
        objs[3]=new object_(96112,"06/06/2020",3);
        objs[4]=new object_(96113,"06/07/2020",1);
        HashMap<String, object_> map = new HashMap<>();
        for(object_ obj:objs){
            if(map.containsKey(obj.date)){
                map.put(obj.date,new object_(obj.material, obj.date, map.get(obj.date).quantity+obj.quantity));
            }
            else{
                map.put(obj.date,obj);
            }
        }
        System.out.println(map);
        
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM