对一个list分组求和???
Lsit<bean>list=new ArrayList<bean>();
数据
username flow(流量/kb)
zhanggsan 100
zhanggsan 100
zhanggsan 100
lisi 200
要求结果
username flow(流量/kb)
zhangdan 300
lisi 200 数据 arraylist
[解决办法]
搞定了,不知道是不是楼主想要的,我运行过了,符合楼主题目的要求
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class Sum
{
public static void main(String[] args)
{
Bean bean1 = new Bean();
Bean bean2 = new Bean();
Bean bean3 = new Bean();
Bean bean4 = new Bean();
bean1.setName("zhangsan");
bean1.setFlow(100);
bean2.setName("zhangsan");
bean2.setFlow(100);
bean3.setName("zhangsan");
bean3.setFlow(100);
bean4.setName("lisi");
bean4.setFlow(200);
List<Bean> list = new ArrayList<Bean>();
list.add(bean1);
list.add(bean2);
list.add(bean3);
list.add(bean4);
Sum s = new Sum();
Map<String, Integer> map;
map = s.sum(list);
Set<String> set = map.keySet();
System.out.println("username flow");
for (Iterator<String> iter = set.iterator(); iter.hasNext();)
{
String key = (String)iter.next();
Integer value = (Integer)map.get(key);
System.out.println(key + " " + value);
}
}
public Map<String, Integer> sum(List<Bean> list)
{
Map<String, Integer> map = new HashMap<String, Integer>();
for (int i=0; i<list.size(); i++)
{
if (null == map.get(list.get(i).getName()))
{
map.put(list.get(i).getName(), list.get(i).getFlow());
}
else
{
Integer in = (Integer)map.get(list.get(i).getName());
in = new Integer(in.intValue() + list.get(i).getFlow());
map.put(list.get(i).getName(), in);
}
}
return map;
}
}
class Bean
{
private String name;
private int flow;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getFlow()
{
return flow;
}
public void setFlow(int flow)
{
this.flow = flow;
}
}