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;
import java.util.stream.Stream;

/**
 * @web http://java-buddy.blogspot.com/
 */
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(lyrics);

        System.out.println("--- Some examples of using Stream ---");
        
        //print all element in Stream<String>
        Stream.of(lyrics.split("[\\P{L}]+"))
            .forEach((String element) -> System.out.println(element));
        
        //count number of element in Stream
        System.out.println("count of words = " + 
            Stream.of(lyrics.split("[\\P{L}]+")).count());
        
        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}]+"))
                .map(String::toLowerCase);
        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}]+"))
                .max(String::compareToIgnoreCase);
        if(max.isPresent()){
            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}]+"))
                .filter(s->s.startsWith("c")).findFirst();
        if(startsWithC.isPresent()){
            System.out.println("the first word starts with 'c' = " + startsWithC.get());
        }
    }

}



No comments:

Post a Comment