RecursiveTask结果到ConcurrentMap

时间:2018-04-04 08:51:30

标签: java concurrency fork-join recursivetask

我试图创建let columnsForModule = [...this.state.columnsForModule]; let columnForModule = this.state.Columns.map(column => ({...column})); // deep copy

我将这篇文章用作Reference

RecursiveTask<Map<Short, Long>>

有人可以帮助我public class SearchTask2 extends RecursiveTask<Map<Short, Long>> { private final int majorDataThreshold = 16000; private ConcurrentNavigableMap<Short, Long> dataMap; private long fromRange; private long toRange; private boolean fromInclusive; private boolean toInclusive; public SearchTask2(final Map<Short, Long> dataSource, final long fromRange, final long toRange, final boolean fromInclusive, final boolean toInclusive) { System.out.println("SearchTask :: "); this.dataMap = new ConcurrentSkipListMap<>(dataSource); this.fromRange = fromRange; this.toRange = toRange; this.fromInclusive = fromInclusive; this.toInclusive = toInclusive; } @Override protected Map<Short, Long> compute() { System.out.println("SearchTask :: compute "); //Map<Short, Long> result = new HashMap<>(); int size = dataMap.size(); if (size > majorDataThreshold + 2500) { return ForkJoinTask.invokeAll(createSubtasks()).parallelStream().map(ForkJoinTask::join) .collect(Collectors.toConcurrentMap(keyMapper, valueMapper)); //.forEach(entry -> result.put( entry.getKey(), (Long) entry.getValue())); } return search(); } private List<SearchTask2> createSubtasks() { final short lastKey = dataMap.lastKey(); final short midkey = (short) (lastKey / 2); final short firstKey = dataMap.firstKey(); final List<SearchTask2> dividedTasks = new ArrayList<>(); dividedTasks.add(new SearchTask2(new HashMap<>(dataMap.subMap(firstKey, true, midkey, false)), fromRange, toRange, fromInclusive, toInclusive)); dividedTasks.add(new SearchTask2(new HashMap<>(dataMap.subMap(midkey, true, lastKey, true)), fromRange, toRange, fromInclusive, toInclusive)); return dividedTasks; } private HashMap<Short,Long> search(){ //My Search logic for values return new HashMap<>(); } } 和&#39; valueMapper&#39;对于我的结果地图,  我试过了keyMapper

但是它显示了一个错误

Collectors.toConcurrentMap(entry -> entry.getKey(), entry -> entry.getValue())

1 个答案:

答案 0 :(得分:2)

您的ForkJoinTask::join正在返回地图,因此您拥有一组地图。您似乎期待着一系列条目。您可以使用flatMap从地图流中获取条目流,如下所示:

return ForkJoinTask.invokeAll(createSubtasks())
    .parallelStream()
    .map(ForkJoinTask::join)
    .flatMap(map -> map.entrySet().stream())   // you were missing this line
    .collect(
        Collectors.toConcurrentMap(entry -> entry.getKey(), entry -> entry.getValue())
    );

稍微改进一下,你也可以使用方法引用而不是你正在尝试的lambda表达式:

Collectors.toConcurrentMap(Entry::getKey, Entry::getValue)