本文共 1970 字,大约阅读时间需要 6 分钟。
如题,假设有如下表t_info:
name | date | info |
a | 20127-12-20 | xxxx描述 |
b | 20127-12-20 | yyyyy描述 |
c | 20127-12-21 | zzz描述 |
d | 20127-12-22 | mmmm描述 |
如果我们要计算上表中每一天的info个数,name在数据库中我们可以简单解决:
select date --日期,count(*) as num --数量from t_infogroup by date
但是如果我们将上述数据转成了Info对象,那么在程序中应该怎么计算呢?于是就来记录一下~
实现思路:
1、新建一个Map<String,Integer>对象用来存放计算结果,键表示日期,值表示该日期下的对象个数。
2、遍历List中的Info对象,提取对象中的Date字段,判断Map是否存在key为该Date的对象,若不存在,则添加键值对(Date,0),对Map中key为Date的值加1。
3、计算结束,遍历Map打印结果。
下面是代码:
package com.dyi.test;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class SortTest { public static void main(String[] args) { //构造List Listlist = new ArrayList (); initList(list); //构造结果Map,并遍历List得出结果 Map groupList = new HashMap (); for(Info info:list){ String key = info.date; if(!groupList.containsKey(key)){ groupList.put(key, 0); } groupList.put(key, groupList.get(key)+1); } //打印结果 for(String key:groupList.keySet()){ System.out.println("key:"+key+",value:"+groupList.get(key)); } } public static void initList(List list){ list.add(new Info("2017-12-20")); list.add(new Info("2017-12-20")); list.add(new Info("2017-12-21")); list.add(new Info("2017-12-21")); list.add(new Info("2017-12-21")); list.add(new Info("2017-12-22")); list.add(new Info("2017-12-22")); list.add(new Info("2017-12-22")); list.add(new Info("2017-12-22")); list.add(new Info("2017-12-22")); list.add(new Info("2017-12-23")); list.add(new Info("2017-12-23")); list.add(new Info("2017-12-23")); list.add(new Info("2017-12-24")); list.add(new Info("2017-12-25")); }}class Info{ public String date; public String name; public String info; public Info(String date){ this.date = date; }}
下面是打印结果,结果吻合……
这些或简单或复杂的小功能,都可以通过基本类库来完成的,毕竟java的工具类那么多。只是完成时间和性能的差别而已,没看过大牛的写法,自己记录一下吧。
黑夜给了我黑色的眼睛,我却用它寻找光明
转载地址:http://nxurl.baihongyu.com/