代码之家  ›  专栏  ›  技术社区  ›  Harish

在java8中对一组数据进行并行计算?

  •  3
  • Harish  · 技术社区  · 10 年前

    我有一组这样的数据:

    Set<CustomObject> testSet = [{id: a1, qty: 3}, 
                                 {id: a2, qty: 9},
                                 {id: a3, qty: 5},
                                 {id: a4, qty: 8},
                                 {id: a5, qty: 12},
                                 ...
                                 {id: a200, qty: 7}];
    

    ID分为3组,可使用以下方法找到:

    //The getGroup method is implemented in the class CustomObject.
    //I am using hazelcast map to store few id's that are inclusive, and
    //one of the id that is in the request of the api is the current id.
    public String getGroup(String id){
         HazelcastInstance hazelcastInstance = Hazelcast.newHazelcastInstance();
         if(id.equals(this.id)){
           return "currentId";
         }else if(id.equals(hazelcastInstance.getMap("idMap").get(id))){
           return "inclusive";
         } else {
           return "exclusive";
         }
    }
    

    上面的testSet包含大量数据,我想使用Java根据上面的分组方法执行Set中每个对象的数量总和。

    我尝试使用流,但这不允许我使用Java8Streams的groupingBy方法中的getGroup方法。

    1 回复  |  直到 10 年前
        1
  •  3
  •   Ömer Erden Eugen Dück    7 年前

    下面的代码将按分组给出包含和排除数量的总和。

    Map < Object, Integer > resultMap =
        testSet.parallelStream()
        .collect(Collectors.groupingBy(item - > {
                if (item.getId().equals(hazelcastInstance.getMap("idMap").get(id)) 
                        return "inclusive";
                    else
                        return "exclusive";
                },
                Collectors.summingInt(CustomObject::getQty)));
    

    此外,使用时 parallelStream() ,您可以考虑使用 ArrayList 而不是 HashSet