Back Home

Stream

  • Stream's provide a scala-esque efficient and concise way to work with collections
  • Streams are designed to work with Java lambda expressions.

Obtaining a Stream From a Collection Stream Processing Phases Stream.filter() Stream.map() Stream.collect() Stream.min() and Stream.max() Stream.count() Stream.reduce()

Obtaining a Stream from a Collection

List<String> items = new ArrayList<String>();
 
items.add("one");
items.add("two");
items.add("three");
 
Stream<String> stream = items.stream();

Stream Processing Phases

Once you have obtained a Stream instance from a Collection instance, you use that stream to process the elements in the collection.

Processing the elements in the stream happens in two steps / phases:

  • Configuration
    • Filters
    • mappings
  • Processing

Finish the rest of the tutorial here http://tutorials.jenkov.com/java-collections/streams.html

List<String> names =newArrayList<>();
for(Student student : students){
if(student.getName().startsWith("A")){
names.add(student.getName());
}
}

There is nothing special about this code. This is a traditional Java external iterations example. Now, have a look at the below code. This line is doing exactly the same thing but we can't see any iteration logic here and hence it is called as internal iterations.

List<string> names = students.stream().map(Student::getName).filter(name->name.startsWith("A"))
.collect(Collectors.toList());

Async

With a Return Value

  • CompletableFuture.supplyAsync() is your the means to call an async function and return the result (or error) . It takes a Supplier<T> and returns CompletableFuture<T> where T is the type of the value obtained by calling the given supplier -
// Run a task specified by a Supplier object asynchronously
CompletableFuture<String> future = CompletableFuture.supplyAsync(new Supplier<String>() {
    @Override
    public String get() {
        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            throw new IllegalStateException(e);
        }
        return "Result of the asynchronous computation";
    }
});
 
// Block and get the result of the Future
String result = future.get();
System.out.println(result);

Using Java 8’s lambda expression to make the above code more concise

// Using Lambda Expression
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
    try {
        TimeUnit.SECONDS.sleep(1);
    } catch (InterruptedException e) {
        throw new IllegalStateException(e);
    }
    return "Result of the asynchronous computation";
});

Async Error Handling

The library allows you to define a standard retry behavior https://github.com/nurkiewicz/async-retry

ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
RetryExecutor executor = new AsyncRetryExecutor(scheduler).
	retryOn(SocketException.class).
	withExponentialBackoff(500, 2).     //500ms times 2 after each retry
	withMaxDelay(10_000).               //10 seconds
	withUniformJitter().                //add between +/- 100 ms randomly
	withMaxRetries(20);

Also of interest

* https://github.com/jhalterman/failsafe Failsafe

 
java8.txt · Last modified: 2017/12/11 11:32 by root
 
RSS - 200 © CrosswireDigitialMedia Ltd