一种基于对象值将对象列表压缩为的有效方法是什么? [英] What is a efficient way to condense a List of objects to based on an object value?

查看:69
本文介绍了一种基于对象值将对象列表压缩为的有效方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个对象的ArrayList.该对象具有五个字段:id,日期,名称,值,adjusted_value.该列表可能包含多个具有相同名称的条目,而我在设计一种有效的方法时遇到了麻烦,该方法可以基于名称将列表压缩到我将列出相似对象的位置,但是存储的值将是name,sum(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).

是否有一种有效的方法来做到这一点?我当前的方法是在do-while内包含for循环.

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

澄清:

我有一份物品清单:

    {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}
   .
   .
   .

但是,我发现HashMap的put()功能将自动执行我想要的操作,但是现在,如果可能的话,我需要在Javascript中执行此类操作.

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.

推荐答案

您可以定义一个Map,其中键为name,值为对象实例.

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.

如果不只是添加到地图上. map.put(instance.name,instance)

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

这篇关于一种基于对象值将对象列表压缩为的有效方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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