Java机试题:合并表记录(使用java8解题)

数据表记录包含表索引和数值(int范围的正整数),请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出。

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static class Record {
        private int key;
        private int value;

        public int getKey() {
            return key;
        }

        public void setKey(int key) {
            this.key = key;
        }

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            this.value = value;
        }
    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int num =  Integer.valueOf(sc.nextLine());
        List<Record> list = new ArrayList<Record>();

        for (int n = 0; n < num; n++) {
            String str = sc.nextLine();
            String[] strs = str.split(" ");
            int key = Integer.valueOf(strs[0]);
            int value = Integer.valueOf(strs[1]);
            Record record = new Record();
            record.setKey(key);
            record.setValue(value);
            list.add(record);
        }
        // 进行分组
        Map<Integer, List<Record>> map = list.stream().collect(Collectors.groupingBy(o -> o.getKey()));
        // 遍历map输出
        List<Record> ret = new ArrayList<Record>();
        for (Map.Entry<Integer, List<Record>> entry :  map.entrySet()) {
            Record record = new Record();
            record.setKey(entry.getKey());
            // 分组后求和
            record.setValue(entry.getValue().stream().mapToInt(o-> o.getValue()).sum());
            ret.add(record);
        }
        // 按key升序输出
        ret = ret.stream().sorted(((o1, o2) -> o1.getKey() - o2.getKey())).collect(Collectors.toList());
        for (Record record : ret){
            System.out.println(record.getKey() + " " + record.getValue());
        }
    }
}

 

上一篇:Java8部分特性及list的常见操作


下一篇:java8接口新特性:default、static