Java parallel stream: how to wait for threads for a parallel stream to finish?

前端 未结 3 1071
梦谈多话
梦谈多话 2021-02-04 09:03

So I have a list from which I obtain a parallel stream to fill out a map, as follows:

Map map = new HashMap<>();
List

        
3条回答
  •  被撕碎了的回忆
    2021-02-04 09:20

    I would guess that if it is possible for the stream to still be processing you could try something like:

        List list = new ArrayList<>();
    
        //Putting data from the list into the map
        Map map = list.parallelStream()
                .collect(Collectors.toMap(
                        n -> n.getId(),
                        n -> new TreeNode(n)
                ));
    

    At least now you have a terminal on the stream. You will use multiple threads possible and the mapping is certainly going to be complete.

提交回复
热议问题