二次元配列のストリーム操作

何:

私は2次元配列の下から最高の平均スコアを見つけようとしています:

String[][] scores = { { "Amit", "70" }, { "Arthit", "60" }, { "Peter", "60" }, { "Arthit", "100" } };

出力は: 80(Arthitのスコア(60 + 100)/ 2)

今まで私はアプローチの下に、しかし私はストリームとエレガントな解決策を探していますし、この問題を解決します:

public static void main(String[] args) {
        String[][] scores = { { "Amit", "70" }, { "Arthit", "60" }, { "Peter", "60" }, { "Arthit", "100" } };

        int highestAvg = Integer.MIN_VALUE;
        Function<String[], Integer> function = new Function<String[], Integer>() {
            @Override
            public Integer apply(String[] t) {
                int sum = 0, count = 0;
                for (int i = 0; i < scores.length; i++) {
                    if (t[0].equals(scores[i][0])) {
                        count++;
                        sum += Integer.parseInt(scores[i][1]);
                    }
                }
                int avg = sum / count;
                return highestAvg < avg ? avg : highestAvg;
            }
        };
        System.out.println(Arrays.stream(scores).map(function).max((o1, o2) -> o1.compareTo(o2)).get());
    }

あなたが提案してくださいだろう、ストリームを使用して2次元配列を扱うためのより良い方法は何ですか?

注:私はちょうどあなたの貴重な提案を見て、厳密解を見ているわけではありません。

ernest_k:

あなたはより多くの使用をすることができ、内蔵を含むストリーム機能、平均化およびグループ化コレクター:

Stream.of(scores)
        .collect(
                Collectors.groupingBy(a -> a[0], 
                Collectors.averagingInt(a -> Integer.parseInt(a[1]))))
        .entrySet()
        .stream()
        .max(Entry.comparingByValue())
        .ifPresent(bestScore -> {
                String message = String.format("Best score is %s, by %s", bestScore.getValue(), bestScore.getKey());
                System.out.println(message);
        });

どのプリント Best score is 80.0, by Arthit

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=177631&siteId=1
おすすめ