Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stream Operation of Two dimensional array

I am trying to find the best average score from below two dimensional array:

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

The output is: 80 (Arthit's score (60+100)/2)

Till now I solved this problem with below approach, however I am looking for elegant solution with stream:

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());
    }

Would you please suggest, what's the better approach to handle two dimensional array using stream?

Note: I am not looking the exact solution, just looking your valuable suggestion.

like image 673
Amit Avatar asked Oct 19 '18 14:10

Amit


People also ask

What are the operations of two dimensional array?

A few basic operations necessary for all the two dimensional array are 'initializing the array', 'inserting the value in the array', 'updating the value in the array', and 'deleting a value from the array'.

What are stream operations?

Stream operations are divided into intermediate ( Stream -producing) operations and terminal (value- or side-effect-producing) operations. Intermediate operations are always lazy. Possibly unbounded. While collections have a finite size, streams need not.

What does Arrays stream () do?

The stream(T[] array) method of Arrays class in Java, is used to get a Sequential Stream from the array passed as the parameter with its elements. It returns a sequential Stream with the elements of the array, passed as parameter, as its source.

What is stream () in Java?

A stream is a sequence of objects that supports various methods which can be pipelined to produce the desired result. The features of Java stream are – A stream is not a data structure instead it takes input from the Collections, Arrays or I/O channels.


1 Answers

You can make more use of built-in stream features, including averaging and grouping collectors:

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);
        });

Which prints Best score is 80.0, by Arthit

like image 197
ernest_k Avatar answered Oct 12 '22 15:10

ernest_k