Java:使用.stream将ArrayList <MyObj>转换为TreeMap <String,ArrayList <MyObj >>

Jak*_*ke 1 collections lambda java-8

这是一个Java 8中低级问题:

我在Java 6中有以下代码:

    List <ViewWrapperContentElementTypeProperty> vwPropertyList = getFromDao();


    TreeMap <Long, ArrayList<ViewWrapperContentElementTypeProperty>> mappedProperties = new TreeMap<Long, ArrayList<ViewWrapperContentElementTypeProperty>> ();
    for (ViewWrapperContentElementTypeProperty vwCetP:vwPropertyList)
    {
        if(null==mappedProperties.get(vwCetP.getContentElementTypeId()))
        {

            ArrayList<ViewWrapperContentElementTypeProperty> list = new ArrayList<ViewWrapperContentElementTypeProperty>());
            list.add(vwCetP);
            mappedProperties.put(vwCetP.getContentElementTypeId(), list);
        }
        else
        {
            mappedProperties.get(vwCetP.getContentElementTypeId()).add(vwCetP);
        }

    }
Run Code Online (Sandbox Code Playgroud)

我可以使用vwPropertyList.stream().map()来更有效地实现它吗?

Ale*_* C. 5

看起来你正在寻找按操作分组.幸运的是,Collectors类提供了一种方法:

import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toCollection;    

...

TreeMap<Long, ArrayList<ViewWrapperContentElementTypeProperty>> mappedProperties =
                    vwPropertyList.stream()
                                  .collect(groupingBy(ViewWrapperContentElementTypeProperty::getContentElementTypeId, 
                                                      TreeMap::new,
                                                      toCollection(ArrayList::new)));
Run Code Online (Sandbox Code Playgroud)

我使用了重载版本groupingBy,您可以在其中提供特定的地图实现(如果您确实需要TreeMap).

另外,toList()收集器返回List(这是一个ArrayList,但它是一个实现细节).由于您显然需要指定具体实现,因为您希望将其ArrayList作为值,您可以使用它toCollection(ArrayList::new).