2016-04-15 69 views
0

我有數據的平面文件。一些主要屬性是[國家,州,市,名,姓,年齡,收入,CreditScore,...]多級分組通過Java中每個級別的計數?

我需要以下分組順序:國家 - >州 - >城市 - >年齡

另外,可以說我需要在每個組級別進行計數......可以使用GROUP BY輕鬆地在RDBMS上完成某些操作!但我沒有數據庫(或根本無法使用它),它是平面文件數據。

一種方法做的是使用HashMap的,但在一個一級或二級的偉大工程,爲水平的提高代碼的複雜...

Map<String, Integer> count = new HashMap<String, Integer>(); 
Iterator<RandomObject> i = r.iterator(); 

while (i.hasNext()) { 
    String key=i.next().getName(); 
    if (count.containsKey(key)) { 
     int rr =Integer.valueOf(count.get(key)); 
     rr++; 
     count.put(key, rr); 
    }else{ 
     count.put(key, 1); 
    } 

}  

有沒有在Java中的任何清潔解決方案,這個問題?

回答

1

既然你問了乾淨的解決方案。要做到這一點,最好的方法是使用Java 8

import java.util.List; 
import java.util.Map; 
import java.util.stream.Collectors; 
import java.util.stream.Stream; 
class Student { 

    String stud_id; 
    String stud_name; 
    String stud_location; 

    public String getStud_id() { 
     return stud_id; 
    } 

    public String getStud_name() { 
     return stud_name; 
    } 

    public String getStud_location() { 
     return stud_location; 
    } 



    Student(String sid, String sname, String slocation) { 

     this.stud_id = sid; 
     this.stud_name = sname; 
     this.stud_location = slocation; 

    } 
} 

class Temp 
{ 
    public static void main(String args[]) 
    { 

     Stream<Student> studs = 
     Stream.of(new Student("1726", "John", "New York"), 
       new Student("4321", "Max", "California"), 
       new Student("2234", "Max", "Los Angeles"), 
       new Student("7765", "Sam", "California")); 
     Map<String, Map<Object, List<Student>>> map= studs.collect(Collectors.groupingBy(Student::getStud_name,Collectors.groupingBy(Student::getStud_location))); 
       System.out.println(map);//print by name and then location 
    } 

} 

{最大值= {洛杉磯= [學生@ 214c265e]加利福尼亞= [學生@ 448139f0]},約翰= {紐約= [學生@ 7cca494b] },Sam = {California = [Student @ 7ba4f24f]}}

+0

您如何處理多級別? – gpa

+0

已按照名稱和位置更新了多級別。希望有所幫助。 – Chirag