简体   繁体   中英

java: add object to new ArrayList without need to parameterize the list

I need to add object to new 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;

}

in the line: new ArrayList<MyObject>() I want to add mo Like: new ArrayList<DataSource>().add(mo)

but it is a boolean value (Go figure). is there another way to add value for the first time to not parametrized list? or the only way is this? List<MyObject> initList = new ArrayList<MyObject>(); initList.add(mo); moMap.put(firstLetter,initList);

Thanks,

You can still use the following syntax:

List<MyObject> initList = new ArrayList<MyObject>() {{ add(mo); }}

Or using Google Guava , you can use Lists.newArrayList(mo) .

You should consider using a MultiMap for what you are trying to achieve (a Map whose values are Lists). Note that Apache Common has a MultiMap implementation too, you can also take a look at the DefaultedMap class.

If using google-guava is an option, you can do Lists.newArrayList(mo) .

The documentation is available on the google-guava API page for Lists .

EDIT Non google-guava option:

If google-guava is not an option, you can implement it yourself like this:

public static <T> List<T> newArrayList(T... a) {
    return new ArrayList<T>(Arrays.asList(a));
}     

This uses a combination of varargs and generics to create the array list. Varargs allows you to specify a variable number of parameters to this function. The generic type allows the type of the parameters to be captured and a list of corresponding type to be returned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM