Пример #1
0
  @Test
  public void reduce() {
    IntStream stream = IntStream.of(1, 2, 3, 4);

    assertEquals(10, stream.reduce(0, (a, b) -> a + b));

    Stream<Integer> stream2 = Arrays.asList(1, 2, 3, 4).stream();

    stream2.reduce(0, (a, b) -> a + b);

    // obviously the operations can be more complex :)

    Stream<Integer> stream3 = Arrays.asList(1, 2, 3, 4).stream();

    // reduce is a superset of map :D
    System.err.println(
        stream3.reduce(
            new ArrayList<Integer>(),
            (List<Integer> a, Integer b) -> {
              a.add(b);
              return a;
            },
            (a, b) -> {
              List<Integer> c = new ArrayList<>(a);
              c.addAll(b);
              return c;
            }));
  }
Пример #2
0
  @Test
  public void _08_리덕션() {
    Stream<Integer> values = Stream.of(digits);
    // x 이전값, y 지금 요소 (v0 + v1 + v2.....)
    Optional<Integer> sum = values.reduce((x, y) -> x + y);

    assertThat(sum, is(Optional.of(366)));
  }
Пример #3
0
 public String getStatRow(String delimiter) {
   Stream<String> pValues = stats.stream().map(s -> Double.toString(s.getPValue()));
   String row = pValues.reduce((s, t) -> s + delimiter + t).get();
   return this.toString() + delimiter + row;
 }
 @Test(expectedExceptions = MonetaryException.class)
 public void shouldMaxMoneratyExceptionWhenHasDifferenctsCurrencies() {
   Stream<MonetaryAmount> stream = streamCurrencyDifferent();
   stream.reduce(max()).get();
 }
 @Test(expectedExceptions = NullPointerException.class)
 public void shouldMaxWithNPEWhenAnElementIsNull() {
   Stream<MonetaryAmount> stream = streamNull();
   stream.reduce(max()).get();
 }
 @Test
 public void shouldMaxCorretly() {
   Stream<MonetaryAmount> stream = StreamFactory.streamNormal();
   MonetaryAmount max = stream.reduce(max()).get();
   Assert.assertTrue(max.getNumber().intValue() == 10);
 }
 @Test
 public void shouldMinCorretly() {
   Stream<MonetaryAmount> stream = streamNormal();
   MonetaryAmount min = stream.reduce(min()).get();
   Assert.assertTrue(min.getNumber().intValue() == 0);
 }
 @Test
 public void shouldSumCorrectly() {
   Stream<MonetaryAmount> stream = streamNormal();
   MonetaryAmount sum = stream.reduce(sum()).get();
   Assert.assertTrue(sum.getNumber().intValue() == 20);
 }
 public static Optional<String> longestArtistNameByReduce(Stream<String> names) {
   return names.reduce((acc, x) -> x.length() > acc.length() ? x : acc);
 }
 public int addUp(Stream<Integer> numbers) {
   return numbers.reduce((acc, element) -> acc + element).get().intValue();
 }