我写代码有个癖好,总想要一步完成所有的事情。垃圾癖好。
一步构建Map。
//一个值
Collections.singletonMap(key,value);
//多个值,一开始使用内部类的方法,but看到说这种写法会创建class文件
new HashMap<>(){{
put(key,value);
}}
//换种写法,Stream咔咔咔,舒服,好像代码更多了,管他呢
Stream.of(new AbstractMap.SimpleEntry<>(key1,val1)
, new AbstractMap.SimpleEntry<>(key2,val2))
.collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue))
//but这个toMap吧,值一样的情况是要报错的,要给个mergeFunction,like this
itemList.stream().filter(Objects::nonNull).filter(e-> !StringUtils.isEmpty(e.getLoanId())).collect(Collectors.toMap(OrderItem::getLoanId,OrderItem::getLoanId,(olderValue, newValue)->newValue));
//第三种,构造器模式,guava,guava!
ImmutableMap.<String,String>builder().put(k1,v1).put(k2,v2).build());