2017-04-25 71 views
-1

目標做1組:
通過爲數據成員_age通過使用Java如何通過使用Java

做一團,然後_amount

結果應該是:

age  amount 
--------------- 
    0   8 
    1   8 
    2   8 
    3   8 

問題:
我沒想到在java中執行它會比C#更困難。

基於從這個page的靈感,我試圖讓group by但它沒有工作。

部分什麼我缺少

謝謝!


import java.util.ArrayList; 
import java.util.List; 
import java.util.stream.Collectors; 

public class JavaApplication22 
{ 

    /** 
    * @param args the command line arguments 
    */ 
    public static void main(String[] args) 
    { 
     List<Test> _Test = new ArrayList<>(); 
     _Test.add(new Test(0, "df", 4)); 
     _Test.add(new Test(0, "we", 4)); 
     _Test.add(new Test(1, "df", 4)); 
     _Test.add(new Test(1, "we", 4)); 
     _Test.add(new Test(2, "df", 4)); 
     _Test.add(new Test(2, "we", 4)); 
     _Test.add(new Test(3, "df", 4)); 
     _Test.add(new Test(3, "we", 4)); 


     // This one below is error 
     Map<String, Integer> sum = _Test.stream().collect(Collectors.groupingBy(Test::get, Collectors.summarizingInt(Test::get))); 


    } 

} 

public class Test 
{ 
    private int _age; 
    private String _sex; 
    private int _amount; 

    public Test(int age, String sex, int amount) 
    { 
     _age = age; 
     _sex = sex; 
     _amount = amount; 
    } 

    public int getAge() 
    { 
     return _age; 
    }  

    public String getSex(String sex) 
    { 
     return _sex; 
    }  

    public int getAmount() 
    { 
     return _amount; 
    }  
} 
+0

請解釋[ 「但它沒有工作」(http://importblogkit.com/2015/07/does-not-work/ )。 – Pshemo

+0

我試圖改成summingInt,並添加了方法「getAge」,但它仍然不起作用 –

回答

1

代碼中幾乎沒有問題。

  1. 對於映射

    age  amount 
    --------------- 
        0   8 
        1   8 
        2   8 
        3   8 
    

    更適合類型將是Map<Integer, Integer>代替Map<String, Integer>

  2. Collectors.summarizingInt將產生IntSummaryStatistics。要獲得只有整數的總和,請使用Collectors.summingInt
  3. Test類中沒有get方法。如果您想要使用getAgegetSexgetAmount,則需要更具體。

所以,你可能正在尋找:

Map<Integer, Integer> sum = _Test //<- type of key should be Integer, not String 
     .stream() 
     .collect(
      Collectors.groupingBy(
       Test::getAge, // <- grouping by age 
       Collectors.summingInt(Test::getAmount) //<-use summingInt instead of summarizingInt 
                 // to sum amount attribute 
      ) 
     ); 
+0

謝謝你們的幫助! –

0

使用地圖將是一個更好的辦法。使用Age作爲與計數器相對應的關鍵字。如果存在密鑰,則增加計數器,否則插入密鑰並將計數器設置爲1.

+0

即時通訊使用語法代碼映射 –