Java 8映射列表按键映射列表

时间:2018-05-25 08:30:15

标签: java java-8 java-stream

我有以下Java代码:

List<BaseQuery> queries; 

Map<Long, List<BaseQuery>> map = new HashMap<>();
for (BaseQuery query : queries) {
    List<BaseQuery> queryList = map.get(query.getCharacteristicId());
    if(queryList == null) {
        queryList = new ArrayList<>();
        map.put(query.getCharacteristicId(), queryList);
    }
    queryList.add(query);
}

您能否展示如何将其转换为Java 8和流?

2 个答案:

答案 0 :(得分:9)

就像groupingBy一样简单:

queries.stream()
       .collect(Collectors.groupingBy(BaseQuery::getCharacteristicId));

这将创建一个List<BaseQuery>作为值,隐含地:

queries.stream()
       .collect(Collectors.groupingBy(
            BaseQuery::getCharacteristicId,
            Collectors.toList()));

但是如果你想要保证可变List

queries.stream()
       .collect(Collectors.groupingBy(
            BaseQuery::getCharacteristicId,
            Collectors.toCollection(ArrayList::new)));

答案 1 :(得分:0)

在Java 8中,您可以作为@Eugene的答案。在Java 7中,您可以按以下方式使用 org.apache.commons.collections.CollectionUtils

List<String> idList = (List<String>) CollectionUtils.collect(objectList, 
                                new BeanToPropertyValueTransformer("id"));