Created
October 23, 2024 19:10
-
-
Save muhdkhokhar/135b549f23dfd4b2aea9b06cdec1e697 to your computer and use it in GitHub Desktop.
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
import java.util.List; | |
import java.util.concurrent.CompletableFuture; | |
import java.util.concurrent.ExecutionException; | |
import java.util.stream.Collectors; | |
public class ParallelProcessingExample { | |
public static void main(String[] args) throws InterruptedException, ExecutionException { | |
List<Integer> list1 = List.of(1, 2, 3); | |
List<Integer> list2 = List.of(4, 5, 6); | |
List<Integer> list3 = List.of(7, 8, 9); | |
// Process each list asynchronously and get a CompletableFuture for each | |
CompletableFuture<List<String>> future1 = CompletableFuture.supplyAsync(() -> processList1(list1)); | |
CompletableFuture<List<String>> future2 = CompletableFuture.supplyAsync(() -> processList2(list2)); | |
CompletableFuture<List<String>> future3 = CompletableFuture.supplyAsync(() -> processList3(list3)); | |
// Combine the results using allOf and then gather the results into a list | |
CompletableFuture<List<List<String>>> allFutures = CompletableFuture.allOf(future1, future2, future3) | |
.thenApply(voidResult -> List.of(future1.join(), future2.join(), future3.join())); | |
// Get the combined results | |
List<List<String>> results = allFutures.get(); | |
// Flatten the results into a single list if needed | |
List<String> combinedResults = results.stream() | |
.flatMap(List::stream) | |
.collect(Collectors.toList()); | |
System.out.println("Combined Results: " + combinedResults); | |
} | |
private static List<String> processList1(List<Integer> list) { | |
return list.stream() | |
.map(item -> "Processed List 1 item: " + item) | |
.collect(Collectors.toList()); | |
} | |
private static List<String> processList2(List<Integer> list) { | |
return list.stream() | |
.map(item -> "Processed List 2 item: " + item) | |
.collect(Collectors.toList()); | |
} | |
private static List<String> processList3(List<Integer> list) { | |
return list.stream() | |
.map(item -> "Processed List 3 item: " + item) | |
.collect(Collectors.toList()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment