Java 8 – reduce
Java 8 – reduce
Metoda reduce() to metoda która wywołuje przekazaną funkcję względem wartości przyrostowej z każdego wywołania i kolejnego elementu tablicy w celu sprowadzenia tej tablicy do pojedynczej wartości. Operacje wykonywane są od lewej do prawej:
public class Person { private final String name; private final int age; public Person(final String name, final int age) { this.name = name; this.age = age; } // getters & setters @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } }
final List<Person> persons = Arrays.asList( new Person("Max" , 18), new Person("Peter" , 23), new Person("Pamela" , 24), new Person("David" , 12) );
Wyświetlamy sumę wieku dla wszystkich osób:
final Integer sumAges = persons .stream() .mapToInt(Person::getAge) .reduce( 0, (sum, age) -> sum + age ); System.out.println(sumAges); // 77
lub inaczej:
persons .stream() .mapToInt(Person::getAge) .reduce(Integer::sum) .ifPresent(x -> System.out.println(x)); //.ifPresent(System.out::print);
Łączymy imiona w jeden ciąg tekstowy rozdzielając je spacją:
// not optimized because of concat string in loop String concatNames = persons .stream() .map(Person::getName) .reduce("", (s1, s2) -> s1 + " " + s2 ); System.out.println(concatNames); // Max Peter Pamela David
bardziej optymalnie – nie powinno łączyć się ciągów tekstowych w pętli za pomocą operatora konkatenacji:
// optimized, better solution StringBuilder concatNamesOptimezed = persons .stream() .map(Person::getName) .map(name -> " " + name) .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append ); System.out.println(concatNamesOptimezed); // Max Peter Pamela David
Inny przykład – sumowanie liczb:
class StatisticsUtility { public static int addIntData(int num1, int num2) { return num1 + num2; } } int[] array = {1,2,3,4,5}; int startValue = 0; int sum = Arrays.stream(array).reduce(startValue, (x,y) -> x+y); System.out.println(sum); // 15 sum = Arrays.stream(array).reduce(startValue, Integer::sum); System.out.println(sum); // 15 sum = Arrays.stream(array).reduce(startValue, StatisticsUtility::addIntData); System.out.println(sum); // 15
Leave a comment