public class Test {
String ag1;
String ag2;
String ag3;
public String getAg1() {
return ag1;
}
public void setAg1(String ag1) {
this.ag1 = ag1;
}
public String getAg2() {
return ag2;
}
public void setAg2(String ag2) {
this.ag2 = ag2;
}
public String getAg3() {
return ag3;
}
public void setAg3(String ag3) {
this.ag3 = ag3;
}
}
public static void main(String[] args) {
List<Test> testList = new ArrayList<>();
Test test1 = new Test();
test1.setAg1("az");
test1.setAg2("sx");
test1.setAg3("03");
testList.add(test1);
Test test2 = new Test();
test2.setAg1("bf");
test2.setAg2("dc");
test2.setAg3("03");
testList.add(test2);
Test test3 = new Test();
test3.setAg1("fv");
test3.setAg2("hn");
test3.setAg3("03");
testList.add(test3);
Map<String, Test> map = new HashMap<>();
if(testList != null && testList.size() >= 1){
map = testList.stream().collect(Collectors.toMap(k -> String.format("%s|%s",k.getAg1(),k.getAg2()), k -> k));
}
System.out.println(map);
Map<String, Test> map2 = new HashMap<>();
if(testList != null && testList.size() >= 1){
map2 = testList.stream().collect(Collectors.toMap(Test::getAg1, k -> k));
}
System.out.println(map2);
}
输出:
{bf|dc=com.hbis.ttie.mal.rest.Test@7d4793a8, fv|hn=com.hbis.ttie.mal.rest.Test@449b2d27, az|sx=com.hbis.ttie.mal.rest.Test@5479e3f}
{fv=com.hbis.ttie.mal.rest.Test@449b2d27, bf=com.hbis.ttie.mal.rest.Test@7d4793a8, az=com.hbis.ttie.mal.rest.Test@5479e3f}
注意:
map2 = testList.stream().collect(Collectors.toMap(Test::getAg1, k -> k));其中的Ag1的值必须唯一,否则会报错
public static void main(String[] args) {
List<Test> testList = new ArrayList<>();
Test test1 = new Test();
test1.setAg1("az");
test1.setAg2("sx");
test1.setAg3("03");
testList.add(test1);
Test test2 = new Test();
test2.setAg1("az");
test2.setAg2("dc");
test2.setAg3("03");
testList.add(test2);
Test test3 = new Test();
test3.setAg1("fv");
test3.setAg2("hn");
test3.setAg3("03");
testList.add(test3);
Map<String, Test> map2 = new HashMap<>();
if(testList != null && testList.size() >= 1){
map2 = testList.stream().collect(Collectors.toMap(Test::getAg1, k -> k));
}
System.out.println(map2);
}
输出:
Exception in thread "main" java.lang.IllegalStateException: Duplicate key com.hbis.ttie.mal.rest.Test@7d4793a8
at java.util.stream.Collectors.lambda$throwingMerger$0(Collectors.java:133)
at java.util.HashMap.merge(HashMap.java:1254)
at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1382)
at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:482)
at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:472)
at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
at com.hbis.ttie.mal.rest.Test.main(Test.java:65)