-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
2.1. Понятие редукции. Произвольный Collector для подсчета
- Loading branch information
Showing
2 changed files
with
58 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
24
src/test/java/ru/job4j/stream/CollectorArithmeticTest.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} | ||
} |