2016-04-15 67 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