Skip to content

Commit 743f6c8

Browse files
forketyforkpivovarit
authored andcommitted
Added example for Supplier lazy generation, corrected the reduce example (eugenp#638)
1 parent 9ae8b34 commit 743f6c8

1 file changed

Lines changed: 23 additions & 3 deletions

File tree

‎core-java-8/src/test/java/com/baeldung/functionalinterface/FunctionalInterfaceTest.java‎

Lines changed: 23 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,18 @@
11
package com.baeldung.functionalinterface;
22

3-
import org.junit.Test;
4-
53
import java.util.Arrays;
64
import java.util.HashMap;
75
import java.util.List;
86
import java.util.Map;
7+
import java.util.concurrent.TimeUnit;
98
import java.util.function.Function;
9+
import java.util.function.Supplier;
1010
import java.util.stream.Collectors;
1111
import java.util.stream.Stream;
1212

13+
import com.google.common.util.concurrent.Uninterruptibles;
14+
import org.junit.Test;
15+
1316
import static org.junit.Assert.*;
1417

1518
public class FunctionalInterfaceTest {
@@ -157,7 +160,7 @@ public void whenUsingBinaryOperatorWithStreamReduce_thenResultIsSumOfValues() {
157160
List<Integer> values = Arrays.asList(3, 5, 8, 9, 12);
158161

159162
int sum = values.stream()
160-
.reduce(0, (acc, value) -> acc + value);
163+
.reduce(0, (i1, i2) -> i1 + i2);
161164

162165
assertEquals(37, sum);
163166

@@ -175,5 +178,22 @@ public void whenComposingTwoFunctions_thenFunctionsExecuteSequentially() {
175178

176179
}
177180

181+
public double squareLazy(Supplier<Double> lazyValue) {
182+
return Math.pow(lazyValue.get(), 2);
183+
}
184+
185+
@Test
186+
public void whenUsingSupplierToGenerateValue_thenValueIsGeneratedLazily() {
187+
188+
Supplier<Double> lazyValue = () -> {
189+
Uninterruptibles.sleepUninterruptibly(1000, TimeUnit.MILLISECONDS);
190+
return 9d;
191+
};
192+
193+
double valueSquared = squareLazy(lazyValue);
194+
195+
assertEquals(81d, valueSquared, 0);
196+
197+
}
178198

179199
}

0 commit comments

Comments
 (0)