1 回答
TA贡献1848条经验 获得超2个赞
通过使用下面的 java-7 是您的问题的一个示例,将 List 转换为具有唯一键和重复值的 Map,它们求和fooNumber并转换为List
Foo.java
class Foo{
private String nameFoo;
private String numberOfFoo;
public Foo() {}
public Foo(String nameFoo, String numberOfFoo) {
this.nameFoo=nameFoo;
this.numberOfFoo=numberOfFoo;
}
public String getNameFoo() {
return nameFoo;
}
public void setNameFoo(String nameFoo) {
this.nameFoo = nameFoo;
}
public String getNumberOfFoo() {
return numberOfFoo;
}
public void setNumberOfFoo(String numberOfFoo) {
this.numberOfFoo = numberOfFoo;
}
@Override
public String toString() {
return "Foo [nameFoo=" + nameFoo + ", numberOfFoo=" + numberOfFoo + "]";
}
}
主.java
public class MainClass {
public static void main(String[] args) {
Foo f1 = new Foo();
f1.setNameFoo("tony");
f1.setNumberOfFoo(100);
Foo f2 = new Foo();
f2.setNameFoo("tony");
f2.setNumberOfFoo(200);
Foo f3 = new Foo();
f3.setNameFoo("cap");
f3.setNumberOfFoo(500);
List<Foo> l = Arrays.asList(f1,f2,f3);
Map<String,List<Foo>> m = new HashMap<>();
List<Foo> result = new ArrayList<>();
for(Foo f:l) {
if(m.get(f.getNameFoo())==null) {
List<Foo> templist = new ArrayList<>();
templist.add(f);
m.put(f.getNameFoo(), templist);
}else {
List<Foo> list =m.get(f.getNameFoo());
list.add(f);
m.put(f.getNameFoo(), list);
}
}
for(String s : m.keySet()) {
Foo fin = new Foo();
Integer fooNumber =0;
for(Foo foo : m.get(s)) {
fooNumber = fooNumber+Integer.valueOf(foo.getNumberOfFoo());
fin.setNameFoo(foo.getNameFoo());
fin.setNumberOfFoo(fooNumber.toString());
}
result.add(fin);
}
System.out.println(result); //[Foo [nameFoo=tony, numberOfFoo=300], Foo [nameFoo=cap, numberOfFoo=500]]
}
}
添加回答
举报