2015/5/3 ã«ç¶ãã£ã½ãã®ãæ¸ãã¾ãã â リストを項目ごとに集計する - Java8ばーじょん - 日々常々
ãã¼ã¿ãã³ã¼ããã¨ã«éè¨ãããã¨ã£ã¦ã®ã¯çµæ§ããããã¾ãã
ä¾ãã°ãããªãã¼ã¿ãâ¦
code | name | value |
---|---|---|
A01 | hoge | 100 |
A01 | piyo | 200 |
A02 | hoge | 300 |
A03 | hoge | 400 |
A03 | piyo | 500 |
codeãã¨ã«éè¨ãã¦ãããããã
code | value |
---|---|
A01 | 300 |
A02 | 300 |
A03 | 900 |
ç¾å ´ã§ããè¦ãã®ã¯ãããªæãã«ãªã£ã¦ã¾ãã
// ãã¼ã¿ã¯ããã®ãªã¹ãã«å ¥ã£ã¦ãã¦ãã¨ã§ã class Data { String code; String name; int value; } public List<Data> summary(List<Data> list) { List<Data> result = new ArrayList<>(); Data data = null; for (Data d : list) { if (data == null || !data.code.equals(d.code)) { if (data != null) { result.add(data); } data = new Data(); data.code = d.code; } data.value += d.value; } if (data != null) { result.add(data); } return result; }
ä¸è¬çã«ã©ãããã®ãã¯ç¥ããªãã§ãããç§ã®ç¾å ´ã§ã¯ããã¬ã¤ã¯å¦çãã¨ãè¨ããã¦ã¾ããã³ã¼ããå¤ããã¿ã¤ãã³ã°ã§ãã¬ã¤ã¯ããã¨ããããªæå³ãããã§ãã
åã®Dataãä¿æããªããcodeãå¤ãã£ã¦ããããæ¯è¼ããå¤ãã£ã¦ãããçµæãªã¹ãã«åã®Dataã追å ãã¦æ°ããDataãä½ããcodeãå¤ãã£ã¦ããªãã£ããåã®Dataã«ãvalueãå ç®ãããã«ã¼ããçµãã£ããçµæã«æå¾ã¾ã§æ®ã£ã¦ãDataã追å ãããè¨èã§æ¸ãã¨ããããããªãâ¦ã
ãã¼ã¿ã¯å
ã
RDBã«å
¥ã£ã¦ããããã®ã§ããéè¨ã¯SQLã§ããã°è¯ãã®ã«ã¼ãã¨æããªãã¯ãªãã®ã§ããããªããããã¾ããããªãã§ãããåå¾ãããã¼ã¿ãããã«å å·¥ããªããéè¨ããã¨ããããã®ã§ããã®è¾ºã¯ä¸æ¦ã«ã¯è¨ããªãã¨ãããããã¾ãããã¯ã¨ããããç½®ãã¦ããã¾ãã
ãã®å¦çã¯ã ãããå®å½¢çã«æ¸ãããã®ã§ããã©ãæ£ç´æå³ãåããã«ãããããããã°ã£ã¦ãã®ãè¦ã¾ãããããªé¢åãªãã¨ãã£ã¦ãããã°ã£ã¦ãä»æ¹ãªãã¨æãã®ã§ããã§ããããããã®ã®å
¸åçãªã®ã£ã¦ã©ãæ¸ããã®ãªãã ããã
ç§ã¯ãããªãµãã«æ¸ããããã¾ãã
public static List<Data> summary(List<Data> list) { Map<String, Data> map = new LinkedHashMap<>(); for (Data d : list) { if (!map.containsKey(d.code)) { Data data = new Data(); data.code = d.code; map.put(d.code, data); } map.get(d.code).value += d.value; } return new ArrayList<Data>(map.values()); }
å ¥åå¤ãã³ã¼ãã§ã½ã¼ãããã¦ããªãå ´åã®æåãéãã¾ãããããã¯åãã³ã¼ããéè¨ããã®ãç®çã ã¨ããªãã¨ãè¨ã£ã¦ãã¾ããæãã§ããªãããããã¹ãã¼ããªæ¸ãæ¹ãã£ãããæãã¦ä¸ããã¨ãã¨ã¦ãå¬ããâ¦ã