Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
219 views
in Technique[技术] by (71.8m points)

java - What is a efficient way to condense a List of objects to based on an object value?

I have an ArrayList of Objects. The object has five fields: id, date, name, value, adjusted_value. The list may hold multiple entries with the same name, and I am having trouble devising an efficient way to condense the list based on the name to where I will a list of similar objects but the values stored will be name, sum(value), sum(adjusted_value).

Is there an efficient way to do this? My current method has for loops inside of a do-while.

Clarfication:

I have a list of obejcts :

    {id,date,name,value,ajusted_value},
    {1,"10/30/2014","peaches",4,3}
    {2,"10/30/2014","apples",2,2}
    {3,"10/31/2014","peaches",3,1}
    .
    .
    .

I want to condense to list based the name value to one that looks like this:

   {null,null,"peaches",7,4}
   {null,null,"apples",2,2}
   .
   .
   .

However, I found that HashMap's put() functionality will perform what I desire automatically, but now I need to do this sort of action in Javascript if possible.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can define a Map where the key is the name and value is the object instance.

Go through the list and for each instance check whether it exists in the map.

If not just add to the map. map.put(instance.name,instance)

If it's already added to the map just

mapInstance=map.get(instance.name);
mapInstance.value+=instance.value;
mapInstance.adjusted_value+=instance.adjusted_value;

After the loop you have the filled map with grouped data


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...