我需要将对象添加到新的ArrayList:
private Map<String,List<MyObject>> populateMapFromList2(List<MyObject> dataSourceList){
Map<String,List<MyObject>> moMap = new HashMap<String, List<MyObject>>();
for (MyObject mo : dataSourceList){
String firstLetter = (mo.getName().substring(0,1)).toUpperCase();
if (!moMap.containsKey(firstLetter)) {
moMap.put(firstLetter,new ArrayList<MyObject>());
}
moMap.get(firstLetter).add(mo);
}
return moMap;
}
行中:new ArrayList<MyObject>()
我要添加mo
喜欢:new ArrayList<DataSource>().add(mo)
但它是一个 boolean 值(看图)。
还有另一种方法可以首次向非参数化列表添加值吗?
或者这是唯一的方法?
List<MyObject> initList = new ArrayList<MyObject>();
initList.add(mo);
moMap.put(firstLetter,initList);
谢谢
最佳答案
您仍然可以使用以下语法:
List<MyObject> initList = new ArrayList<MyObject>() {{ add(mo); }}
或者使用Google Guava,您可以使用Lists.newArrayList(mo)
。
您应该考虑使用 MultiMap对于您想要实现的目标(值为列表的映射)。请注意,Apache Common 有一个 MultiMap实现太,你也可以看看 DefaultedMap类。
关于java:将对象添加到新的ArrayList,无需参数化列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8971223/