'Add to list elements Async in Java
I'm rather new to JAVA and have a problem similar to the one mentioned below, where I want to add elements to an array via async processing. However, the returned array is with size 0 and not the correct size.
// Iterate over the products and transform them asynchronously
List<String> transformed = new ArrayList<>();
for (Product product : products) {
product.transform(rh -> {
transformed.add(rh.result());
});
}
// Check the transformed list.
System.out.println(transformed.size()) // should be 10 but is 0
I could not find a simple tested solution for this. What would be an example implementation for this in JAVA?
Solution 1:[1]
You just have to extends Thread in Product, then implement the function run() with an @Override. That's make you able to do your loop like this :
// Iterate over the products and transform them asynchronously
List<String> transformed = new ArrayList<>();
for (Product product : products) {
transformed.add(product.start());
}
// Check the transformed list.
System.out.println(transformed.size()) // should be 10 but is 0
The .start() start a new Thread who run the méthode run().
You can also give your ArrayList transformed as an attribut for Product then in product .add() in transformed.
Solution 2:[2]
Not sure if I get your question, but one possible way to do it would be using a parallel stream and either using mapping or foreach on top of your products list.
I made some assumptions, just to create an example, but here's how it looks
private void yourMethod(List products){
List<String> transformed = products.parallelStream().map(this::transformation).collect(Collectors.toList());
// Check the transformed list.
System.out.println(transformed.size());
}
private String transformation(Product product){
// do some transformation
return "some transformed";
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Louis |
Solution 2 | Rafael Alexandre Faria |