qué:
Estoy tratando de encontrar la mejor puntuación media desde abajo matriz bidimensional:
String[][] scores = { { "Amit", "70" }, { "Arthit", "60" }, { "Peter", "60" }, { "Arthit", "100" } };
La salida es: 80 (puntuación de Arthit (60 + 100) / 2)
Hasta ahora he resuelto este problema con más adelante enfoque, sin embargo Busco solución elegante con la corriente:
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());
}
¿Por favor sugerir, ¿cuál es el mejor enfoque para manejar matriz de dos dimensiones utilizando corriente?
Nota: No estoy buscando la solución exacta, sólo busca su sugerencia valiosa.
ernest_k:
Puede hacer un mayor uso de las características incorporadas de corriente, incluyendo promedio y la agrupación de los colectores:
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);
});
¿Qué impresiones Best score is 80.0, by Arthit