Thursday, April 17, 2014

Some examples of using Stream of Java 8

This post show some example of using Stream<String> of Java 8; such as splite String to Stream<String> of words, print all element in Stream, count number of element, sort Stream, convert to lower case, find the maximum, and Find the first word starts with.

package java8stream;

import java.util.Optional;

 * @web
public class Java8Stream {

    static String lyrics = "Hello darkness, my old friend,\n"
            + "I've come to talk with you again,\n"
            + "Because a vision softly creeping,\n"
            + "Left its seeds while I was sleeping,\n"
            + "And the vision that was planted in my brain\n"
            + "Still remains\n"
            + "Within the sound of silence.";

    public static void main(String[] args) {
        System.out.println("--- lyrics ---");

        System.out.println("--- Some examples of using Stream ---");
        //print all element in Stream<String>
            .forEach((String element) -> System.out.println(element));
        //count number of element in Stream
        System.out.println("count of words = " + 
        System.out.println("--- Sorted Stream ---");
        Stream<String> sortedStream = Stream.of(lyrics.split("[\\P{L}]+")).sorted();
        sortedStream.forEach((String element) -> System.out.println(element));
        System.out.println("--- Convert to lower case ---");
        Stream<String> sortedStreamLower = Stream.of(lyrics.split("[\\P{L}]+"))
        sortedStreamLower.forEach((String element) -> System.out.println(element));
        System.out.println("--- Find the maximum, ignore case, in Stream<String> ---");
        Optional<String> max = Stream.of(lyrics.split("[\\P{L}]+"))
            System.out.println("max = " + max.get());
        System.out.println("--- Find the first word starts with 'c' ---");
        Optional<String> startsWithC = Stream.of(lyrics.split("[\\P{L}]+"))
            System.out.println("the first word starts with 'c' = " + startsWithC.get());


No comments:

Post a Comment