我有数据的平面文件。一些主要属性是[国家,州,城市,名字,姓氏,年龄,收入,信用评分,......]
我需要遵循灌浆顺序:国家 - >州 - >城市 - >年龄
此外,假设我需要在每个组级别进行计数......使用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中是否有任何干净的解决方案?
答案 0 :(得分: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
}
}
{Max = {Los Angeles = [Student @ 214c265e],California = [Student @ 448139f0]},John = {New York = [Student @ 7cca494b]},Sam = {California = [Student @ 7ba4f24f]}}