Guide to Stream.reduce() (#6372)
* Initial Commit * Update StreamReduceUnitTest.java * Update StreamReduceUnitTest.java * Update StreamReduceUnitTest.java
This commit is contained in:
		
							parent
							
								
									37f9a70441
								
							
						
					
					
						commit
						ca4440d792
					
				| @ -0,0 +1,62 @@ | |||||||
|  | package com.baeldung.streamreduce.application; | ||||||
|  | 
 | ||||||
|  | import com.baeldung.streamreduce.entities.User; | ||||||
|  | import com.baeldung.streamreduce.utilities.NumberUtils; | ||||||
|  | import java.util.ArrayList; | ||||||
|  | import java.util.Arrays; | ||||||
|  | import java.util.List; | ||||||
|  | 
 | ||||||
|  | public class Application { | ||||||
|  | 
 | ||||||
|  |     public static void main(String[] args) { | ||||||
|  |         List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); | ||||||
|  |         int result1 = numbers.stream().reduce(0, (a, b) -> a + b); | ||||||
|  |         System.out.println(result1); | ||||||
|  |          | ||||||
|  |         int result2 = numbers.stream().reduce(0, Integer::sum); | ||||||
|  |         System.out.println(result2); | ||||||
|  | 
 | ||||||
|  |         List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); | ||||||
|  |         String result3 = letters.stream().reduce("", (a, b) -> a + b); | ||||||
|  |         System.out.println(result3); | ||||||
|  |          | ||||||
|  |         String result4 = letters.stream().reduce("", String::concat); | ||||||
|  |         System.out.println(result4); | ||||||
|  | 
 | ||||||
|  |         String result5 = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase()); | ||||||
|  |         System.out.println(result5); | ||||||
|  |          | ||||||
|  |         List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35)); | ||||||
|  |         int result6 = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); | ||||||
|  |         System.out.println(result6); | ||||||
|  |          | ||||||
|  |         String result7 = letters.parallelStream().reduce("", String::concat); | ||||||
|  |         System.out.println(result7); | ||||||
|  |          | ||||||
|  |         int result8 = users.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); | ||||||
|  |         System.out.println(result8); | ||||||
|  |          | ||||||
|  |         List<User> userList = new ArrayList<>(); | ||||||
|  |         for (int i = 0; i <= 1000000; i++) { | ||||||
|  |             userList.add(new User("John" + i, i)); | ||||||
|  |         } | ||||||
|  |          | ||||||
|  |         long t1 = System.currentTimeMillis(); | ||||||
|  |         int result9 = userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); | ||||||
|  |         long t2 = System.currentTimeMillis(); | ||||||
|  |         System.out.println(result9); | ||||||
|  |         System.out.println("Sequential stream time: " + (t2 - t1) + "ms"); | ||||||
|  |          | ||||||
|  |         long t3 = System.currentTimeMillis(); | ||||||
|  |         int result10 = userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); | ||||||
|  |         long t4 = System.currentTimeMillis(); | ||||||
|  |         System.out.println(result10); | ||||||
|  |         System.out.println("Parallel stream time: " + (t4 - t3) + "ms"); | ||||||
|  |          | ||||||
|  |         int result11 = NumberUtils.divideListElements(numbers, 1); | ||||||
|  |         System.out.println(result11); | ||||||
|  |          | ||||||
|  |         int result12 = NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0); | ||||||
|  |         System.out.println(result12); | ||||||
|  |     }     | ||||||
|  | } | ||||||
| @ -0,0 +1,25 @@ | |||||||
|  | package com.baeldung.streamreduce.entities; | ||||||
|  | 
 | ||||||
|  | public class User { | ||||||
|  | 
 | ||||||
|  |     private final String name; | ||||||
|  |     private final int age; | ||||||
|  | 
 | ||||||
|  |     public User(String name, int age) { | ||||||
|  |         this.name = name; | ||||||
|  |         this.age = age; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     public String getName() { | ||||||
|  |         return name; | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     public int getAge() { | ||||||
|  |         return age; | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     @Override | ||||||
|  |     public String toString() { | ||||||
|  |         return "User{" + "name=" + name + ", age=" + age + '}'; | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,52 @@ | |||||||
|  | package com.baeldung.streamreduce.utilities; | ||||||
|  | 
 | ||||||
|  | import java.util.List; | ||||||
|  | import java.util.function.BiFunction; | ||||||
|  | import java.util.logging.Level; | ||||||
|  | import java.util.logging.Logger; | ||||||
|  | 
 | ||||||
|  | public abstract class NumberUtils { | ||||||
|  | 
 | ||||||
|  |     private static final Logger LOGGER = Logger.getLogger(NumberUtils.class.getName()); | ||||||
|  | 
 | ||||||
|  |     public static int divideListElements(List<Integer> values, Integer divider) { | ||||||
|  |         return values.stream() | ||||||
|  |                 .reduce(0, (a, b) -> { | ||||||
|  |                     try { | ||||||
|  |                         return a / divider + b / divider; | ||||||
|  |                     } catch (ArithmeticException e) { | ||||||
|  |                         LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); | ||||||
|  |                     } | ||||||
|  |                     return 0; | ||||||
|  |                 }); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     public static int divideListElementsWithExtractedTryCatchBlock(List<Integer> values, int divider) { | ||||||
|  |         return values.stream().reduce(0, (a, b) -> divide(a, divider) + divide(b, divider)); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     public static int divideListElementsWithApplyFunctionMethod(List<Integer> values, int divider) { | ||||||
|  |         BiFunction<Integer, Integer, Integer> division = (a, b) -> a / b; | ||||||
|  |         return values.stream().reduce(0, (a, b) -> applyFunction(division, a, divider) + applyFunction(division, b, divider)); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     private static int divide(int value, int factor) { | ||||||
|  |         int result = 0; | ||||||
|  |         try { | ||||||
|  |             result = value / factor; | ||||||
|  |         } catch (ArithmeticException e) { | ||||||
|  |             LOGGER.log(Level.INFO, "Arithmetic Exception: Division by Zero"); | ||||||
|  |         } | ||||||
|  |         return result; | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     private static int applyFunction(BiFunction<Integer, Integer, Integer> function, int a, int b) { | ||||||
|  |         try { | ||||||
|  |             return function.apply(a, b); | ||||||
|  |         } | ||||||
|  |         catch(Exception e) { | ||||||
|  |             LOGGER.log(Level.INFO, "Exception occurred!"); | ||||||
|  |         } | ||||||
|  |         return 0; | ||||||
|  |     } | ||||||
|  | } | ||||||
| @ -0,0 +1,126 @@ | |||||||
|  | package com.baeldung.streamreduce.tests; | ||||||
|  | 
 | ||||||
|  | import com.baeldung.streamreduce.entities.User; | ||||||
|  | import com.baeldung.streamreduce.utilities.NumberUtils; | ||||||
|  | import java.util.ArrayList; | ||||||
|  | import java.util.Arrays; | ||||||
|  | import java.util.List; | ||||||
|  | import static org.assertj.core.api.Assertions.assertThat; | ||||||
|  | import org.junit.Test; | ||||||
|  | 
 | ||||||
|  | public class StreamReduceUnitTest { | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenIntegerList_whenReduceWithSumAccumulatorLambda_thenCorrect() { | ||||||
|  |         List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); | ||||||
|  |          | ||||||
|  |         int result = numbers.stream().reduce(0, (a, b) -> a + b); | ||||||
|  |          | ||||||
|  |         assertThat(result).isEqualTo(21); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenIntegerList_whenReduceWithSumAccumulatorMethodReference_thenCorrect() { | ||||||
|  |         List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); | ||||||
|  |          | ||||||
|  |         int result = numbers.stream().reduce(0, Integer::sum); | ||||||
|  |          | ||||||
|  |         assertThat(result).isEqualTo(21); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenStringList_whenReduceWithConcatenatorAccumulatorLambda_thenCorrect() { | ||||||
|  |         List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); | ||||||
|  |          | ||||||
|  |         String result = letters.stream().reduce("", (a, b) -> a + b); | ||||||
|  |          | ||||||
|  |         assertThat(result).isEqualTo("abcde"); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenStringList_whenReduceWithConcatenatorAccumulatorMethodReference_thenCorrect() { | ||||||
|  |         List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); | ||||||
|  |          | ||||||
|  |         String result = letters.stream().reduce("", String::concat); | ||||||
|  |          | ||||||
|  |         assertThat(result).isEqualTo("abcde"); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenStringList_whenReduceWithUppercaseConcatenatorAccumulator_thenCorrect() { | ||||||
|  |         List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); | ||||||
|  |          | ||||||
|  |         String result = letters.stream().reduce("", (a, b) -> a.toUpperCase() + b.toUpperCase()); | ||||||
|  |          | ||||||
|  |         assertThat(result).isEqualTo("ABCDE"); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenUserList_whenReduceWithAgeAccumulatorAndSumCombiner_thenCorrect() { | ||||||
|  |         List<User> users = Arrays.asList(new User("John", 30), new User("Julie", 35)); | ||||||
|  |          | ||||||
|  |         int result = users.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); | ||||||
|  |          | ||||||
|  |         assertThat(result).isEqualTo(65); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenStringList_whenReduceWithParallelStream_thenCorrect() { | ||||||
|  |         List<String> letters = Arrays.asList("a", "b", "c", "d", "e"); | ||||||
|  |          | ||||||
|  |         String result = letters.parallelStream().reduce("", String::concat); | ||||||
|  |          | ||||||
|  |         assertThat(result).isEqualTo("abcde"); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenNumberUtilsClass_whenCalledDivideListElements_thenCorrect() { | ||||||
|  |         List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); | ||||||
|  |          | ||||||
|  |         assertThat(NumberUtils.divideListElements(numbers, 1)).isEqualTo(21); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlock_thenCorrect() { | ||||||
|  |         List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); | ||||||
|  |          | ||||||
|  |         assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); | ||||||
|  |     } | ||||||
|  | 
 | ||||||
|  |     @Test | ||||||
|  |     public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndListContainsZero_thenCorrect() { | ||||||
|  |         List<Integer> numbers = Arrays.asList(0, 1, 2, 3, 4, 5, 6); | ||||||
|  |          | ||||||
|  |         assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 1)).isEqualTo(21); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     @Test | ||||||
|  |     public void givenNumberUtilsClass_whenCalledDivideListElementsWithExtractedTryCatchBlockAndDividerIsZero_thenCorrect() { | ||||||
|  |         List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); | ||||||
|  |          | ||||||
|  |         assertThat(NumberUtils.divideListElementsWithExtractedTryCatchBlock(numbers, 0)).isEqualTo(0); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     @Test | ||||||
|  |     public void givenStream_whneCalleddivideListElementsWithApplyFunctionMethod_thenCorrect() { | ||||||
|  |         List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6); | ||||||
|  |          | ||||||
|  |         assertThat(NumberUtils.divideListElementsWithApplyFunctionMethod(numbers, 1)).isEqualTo(21); | ||||||
|  |     } | ||||||
|  |      | ||||||
|  |     @Test | ||||||
|  |     public void givenTwoStreams_whenCalledReduceOnParallelizedStream_thenFasterExecutionTime() { | ||||||
|  |         List<User> userList = new ArrayList<>(); | ||||||
|  |         for (int i = 0; i <= 1000000; i++) { | ||||||
|  |             userList.add(new User("John" + i, i)); | ||||||
|  |         } | ||||||
|  |         long currentTime1 = System.currentTimeMillis(); | ||||||
|  |         userList.stream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); | ||||||
|  |         long sequentialExecutionTime = System.currentTimeMillis() -currentTime1; | ||||||
|  |         long currentTime2 = System.currentTimeMillis(); | ||||||
|  |         userList.parallelStream().reduce(0, (partialAgeResult, user) -> partialAgeResult + user.getAge(), Integer::sum); | ||||||
|  |         long parallelizedExecutionTime = System.currentTimeMillis() - currentTime2; | ||||||
|  |          | ||||||
|  |         assertThat(parallelizedExecutionTime).isLessThan(sequentialExecutionTime); | ||||||
|  |     } | ||||||
|  | } | ||||||
		Loading…
	
	
			
			x
			
			
		
	
		Reference in New Issue
	
	Block a user