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

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

问题描述

我有一个对象的 ArrayList.该对象有五个字段:id、date、name、value、adjusted_value.该列表可能包含多个具有相同名称的条目,我无法设计一种有效的方法来根据名称将列表压缩到类似对象列表的位置,但存储的值将是名称、总和(值),总和(adjusted_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天全站免登陆