Skip to content

Commit

Permalink
2.1. Понятие редукции. Произвольный Collector для подсчета
Browse files Browse the repository at this point in the history
  • Loading branch information
devvk committed Oct 23, 2024
1 parent 96efbba commit 120986b
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
34 changes: 34 additions & 0 deletions src/main/java/ru/job4j/stream/CollectorArithmetic.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
package ru.job4j.stream;

import java.util.LinkedList;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;

public class CollectorArithmetic {
public static Integer collect(List<Integer> list) {
Supplier<List<Integer>> supplier = LinkedList::new;
BiConsumer<List<Integer>, Integer> consumer = List::add;
BinaryOperator<List<Integer>> merger = (xs, ys) -> {
xs.addAll(ys);
return xs;
};
Function<List<Integer>, Integer> function = (ns) -> {
int result = 1;
for (int i : ns) {
result *= i;
}
return result;
};
return list.stream()
.collect(Collector.of(
supplier,
consumer,
merger,
function)
);
}
}
24 changes: 24 additions & 0 deletions src/test/java/ru/job4j/stream/CollectorArithmeticTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package ru.job4j.stream;

import org.junit.jupiter.api.Test;

import java.util.List;

import static org.assertj.core.api.Assertions.assertThat;

public class CollectorArithmeticTest {

@Test
public void whenWithout0() {
int result = CollectorArithmetic.collect(List.of(1, 2, 3));
int expected = 6;
assertThat(result).isEqualTo(expected);
}

@Test
public void whenWith0() {
int result = CollectorArithmetic.collect(List.of(0, 2, 3));
int expected = 0;
assertThat(result).isEqualTo(expected);
}
}

0 comments on commit 120986b

Please sign in to comment.