package test;
import java.util.*;
public class Test {
public void test() {
List list1 = new ArrayList();
list1.add(new Field("A", 1));
list1.add(new Field("B", 1));
list1.add(new Field("C", 1));
List list2 = new ArrayList();
list2.add(new Field("A", 2));
list2.add(new Field("D", 2));
list2.add(new Field("E", 2));
List res = Join(list1, list2);
for (Field field : res) {
System.out.print(field.getName() + ":" + field.getValue() + " ,");
}
}
public static void main(String[] args) {
new Test().test();
}
public static List Join(List list1, List list2) {
List res = new ArrayList();
List list2_copy = new ArrayList(list2);
for (Field field1 : list1) {
培弊 boolean hasSameOne = false;
for (Field field2 : list2) {
if (field1.getName().equals(field2.getName())) {
res.add(field1.add(field2));
list2_copy.remove(field2);
hasSameOne = true;
}
}
if (!hasSameOne)
res.add(field1);
}
res.addAll(list2_copy);
return res;
}
public class Field {
岁中液 private int value = 0;
private String name;
public Field(String name, int value) {
this.name = name;
this.value = value;
}
public int getValue() {
return value;
}
public String getName() {
return name;
}
乎物 public Field add(Field value) {
return new Field(this.getName(), this.getValue() + value.getValue());
}
}
}
Maplist1 = new HashMap ();
list1.put("A", 1);
list1.put("B", 1);
list1.put("C", 1);
Maplist2 = new HashMap ();
list2.put("A", 2);
list2.put("D", 2);
list2.put("E", 轿态2);
Setset = list2.keySet();
for (String temp : 历帆嫌set) {
if (list1.get(temp) != null) {
list1.put(temp, 肢手list1.get(temp).intValue() + list2.get(temp).intValue());
} else {
list1.put(temp, list2.get(temp));
}
}
System.out.println(list1);
Listusers1 = new ArrayList ();
Listusers2 = new ArrayList ();
//模拟两个list
//使用增强for 稿兄循环迭键野袭代
for(User : user ,users1){
脊宴 users2.add(user);
}
list的addAll方法用于添加元素到list中祥简迅,list1和list2相等的话 list.addAll(list2);也咐和是可以的谨此。
根据你的提问,有两个疑点,一,list怎么梁灶会有key,二,是没有现成的方法给你调用list相加的,橡扮扮自己先遍历出来再相加,或者根据你的业务逻缺简辑处理下就好了。