背景:
今天项目遇到一类场景,跟大家分享下解题过程:已知文件中一组数据如下:
id | user | address | time |
1 | 张三 | 福建省漳州市龙海区 | 2018-05-05 |
2 | 张三 | 福建省福州市闽侯县 | 2018-05-06 |
3 | 李四 | 浙江省温州市苍南县 | 2018-05-07 |
4 | 王五 | 上海市松江区 | 2018-05-03 |
要求以user字段分组,并按time倒序,求出每人最新的结果。
分析思路:
1.文件读取
private static List<Map<String, String>> readDataFromFile(File file) { List<Map<String, String>> result = new ArrayList<>(); String[] titles = new String[]{"id", "user", "address", "time"}; try (BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(file), StandardCharsets.UTF_8))) { boolean firstLine = true; String data; while (null != (data = br.readLine())) { if (firstLine) { firstLine = false; continue; } String[] split = data.split("\\t"); Map<String, String> map = new HashMap<>(); for (int i = 0; i < split.length; i++) { map.put(titles[i], split[i]); } result.add(map); } } catch (Exception e) { e.printStackTrace(); } return result; }
2.数据排序:
private static void orderData(List<Map<String, String>> params) { Map<String, Map<String, String>> data = new HashMap<>(); for (Map<String, String> item : params) { if (data.get("user") == null) { data.put(item.get("user"), item); } elseif (convertTime(data.get("user").get("time")) < convertTime(item.get("time"))) { data.put(item.get("user"), item); } } } private static long convertTime(String time) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); long result = 0L; try { Date date = sdf.parse(time); result = date.getTime(); } catch (Exception e) { e.printStackTrace(); } return result; }
标签:文件,读取,get,item,最新,user,time,new,data From: https://www.cnblogs.com/dork-h/p/16709263.html