这篇文章主要介绍“java中分组统计的实现方法有哪些”,在日常操作中,相信很多人在java中分组统计的实现方法有哪些问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答”java中分组统计的实现方法有哪些”的疑惑有所帮助!接下来,请跟着小编一起来学习吧!
平时工作中,很多时候都会用到对数据进行分组操作,例如一个学生对象,有班级、名字、性别、分数等,需要按班级分组统计,该怎么操作呢?一个合理的算法可以提升不少效率。
//下面是初始化的数据
List<Student> list = new ArrayList<Student>();
Student student1 = new Student("李四1", "女", "一班");
Student student2 = new Student("李四2", "女", "一班");
Student student3 = new Student("李四3", "女", "一班");
Student student4 = new Student("李四4", "男", "一班");
Student student5 = new Student("李四5", "男", "一班");
Student student6 = new Student("李四6", "男", "二班");
Student student7 = new Student("李四7", "男", "二班");
Student student8 = new Student("李四8", "男", "二班");
Student student9 = new Student("李四9", "男", "二班");
list.add(student1);
list.add(student2);
list.add(student3);
list.add(student4);
list.add(student5);
list.add(student6);
list.add(student7);
list.add(student8);
list.add(student9);
在实际开发中合理的利用map自带的方法,能解决很多问题
for (Student stu : list) {
if (!map.containsKey(stu.getProvinceCode())) {
ArrayList<ArrearageDeal> al = new ArrayList<ArrearageDeal>();
map.put(stu.getProvinceCode(), al.add(stu));
} else {
map.get(stu.getProvinceCode()).add(stu);
}
}
Multimap<String, Student> mulMap = ArrayListMultimap.create();
for (Student stu : list) {
mulMap.put(stu.getGrade,stu);
}
毕竟java14都出来了,java8的新特性还是需要多了解
//一行就可以解决
Map<String, List<Student >> collect = list.stream().collect(Collectors.groupingBy(ArrearageDeal::getGrade));
上面三种当时从代码量上来看,java8的最简洁。但是实际开发中结合具体场景来说2、3两种都是不错的选择。
// 分组统计
Map<String, Long> countMap = records.stream().collect(Collectors.groupingBy(o -> o.getProductType() + "_" + o.getCountry(), Collectors.counting()));
List<Record> countRecords = countMap.keySet().stream().map(key -> {
String[] temp = key.split("_");
String productType = temp[0];
String country = temp[1];
Record record = new Record();
record.set("device_type", productType);
record.set("location", country;
record.set("count", countMap.get(key).intValue());
return record;
}).collect(Collectors.toList());
到此,关于“java中分组统计的实现方法有哪些”的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注亿速云网站,小编会继续努力为大家带来更多实用的文章!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。