Java 8 Stream continues…

Sorting

public class SortExample {

public static void main(String[] args) {

List list =Arrays.asList(“a1”, “a2”, “b1”, “c2”, “c1”);

list.stream().filter(s -> s.startsWith(“c”)).map(String::toUpperCase).sorted()
.forEach(System.out::println);

}
}

Output:
C1
C2

Stream.of(): use Stream.of() to create a stream from a bunch of object references.

package com.java.stream;

import java.util.stream.Stream;

public class StreamOfExample {

public static void main(String[] args) {

Stream.of(“a1”, “a2”, “a3”).findFirst().ifPresent(System.out::println);

}
}

Output:a1 

Working on Primitive data Types

Besides regular object streams Java 8 ships with special kinds of streams for working with the primitive data types int, long and double. As you might have guessed it’s IntStream, LongStream and DoubleStream.

IntStreams can replace the regular for-loop utilizing IntStream.range():

package com.java.stream;

import java.util.stream.IntStream;

public class IntStreamExample {

public static void main(String[] args) {

IntStream.range(1, 4).forEach(System.out::println);
}
}

Output:
1
2
3

Leave a Reply

Your email address will not be published. Required fields are marked *