2016-07-29 31 views
2

我有一組數據是這樣的:Java 8中的一組數據的並行計算?

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"; 
    } 
} 

的測試集是具有巨大的數據,我要使用Java根據上面的分組方法執行Set中每個對象的數量總和。

我嘗試使用流,但不允許我在Java 8 Streaming的groupingBy方法中使用getGroup方法。

請指導我如何有效地總結基於組並行處理的數量值。

+1

你如何使用分組的方法可能它不工作,因爲id參數 –

+0

是@Bolzano,我不能在這裏使用,我試圖找到一種方法來組合基於方法的對象和應用sum方法組。 '地圖 sumByType = \t \t \t \t \t測試集 \t \t \t \t .stream() \t \t \t \t .collect( \t \t \t \t Collectors.groupingBy( \t \t \t \t \t CustomObject :: getGroup, \t \t \t \t Collectors.reducing( \t \t \t \t \t \t 0, \t \t \t \t \t CustomObject :: getQty, \t \t \t \t \t整數::總和)));' – Harish

+1

確定第一每getGroup不該創建hazelCast實例我會建議你任何其他的做法,但我想知道你在哪裏計劃getGroup方法的pass ID參數? –

回答

3

這裏是代碼將給包容和獨家數量的總和分組。

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

此外,爲了獲得更好的性能,當使用並行流並測量它時,使用ArrayList而不是HashSet。

+0

非常感謝。我會試試看。 – Harish

+1

它怎麼樣? –

+0

處理它。在某個時候會讓你知道結果。 – Harish