DEV Community

Cover image for Java 8 Stream API on Arrays
Henri Idrovo
Henri Idrovo

Posted on

Java 8 Stream API on Arrays

Java 8 introduced the concept of functional programming. My first instinct when I need to iterate is to use a for-loop. So here are some common operations on arrays using the stream api. I'll reference this post when I need a friendly reminder. USE MORE STREAMS! You can read more about java streams here. Also I'm using the Java 8 method reference syntax, you can read more about that topic here.

Given an array of strings that represent a phone number, format and print each to console.

String[] phoneNumbers = new String[] {"3125550909", "3125557676", "3125552323", "3125556161", "3125554141"};

String[] formattedPhoneNumbers = Arrays.stream(phoneNumbers)
        .map(value -> String.format("1-(%s)-%s-%s", value.substring(0,3), value.substring(3,6), value.substring(6,10)))
        .toArray(String[]::new);

Arrays.stream(formattedPhoneNumbers).forEach(System.out::println);
Enter fullscreen mode Exit fullscreen mode

Given an array of strings that represent zip codes, filter out unwanted zip codes and print remaining to console.

String[] zipCodes = new String[] {"60640","94102", "60602", "94115", "60647", "94140"};

String[] subsetZipCodes = Arrays.stream(zipCodes)
        .filter(value -> value.contains("606"))
        .toArray(String[]::new);

Arrays.stream(subsetZipCodes).forEach(System.out::println);
Enter fullscreen mode Exit fullscreen mode

Given an array of sentences, count the number of occurrences for each word and print to console.

String[] lines = new String[] {
        "toast for breakfast ",
        "sleepy in chicago",
        "tired in the morning",
        "coffee in the morning",
        "sleepy breakfast today",
        "breakfast in chicago" };

Map <String, Integer > wordCount = Arrays.stream(lines)
        .map(w -> w.split("\\s+"))
        .flatMap(Arrays::stream)
        .collect(Collectors.toMap(w -> w, w -> 1, Integer::sum));

wordCount.forEach((k, v) -> System.out.println(String.format("%s ==>> %d", k, v)));
Enter fullscreen mode Exit fullscreen mode

Given an array of names, and a custom NbaPlayer class, create a new array with elements of NbaPlayer type.

String[] names = {"lebron", "kyrie", "doncic", "davis", "lavine"};

class NbaPlayer {
    String name;
    NbaPlayer(String name){
        this.name = name;
    }

    @Override
    public String toString() {
        return "NbaPlayer{" +
                "name='" + name + '\'' +
                '}';
    }
}

NbaPlayer[] players = Arrays.stream(names).map(NbaPlayer::new).toArray(NbaPlayer[]::new);

Arrays.stream(players).forEach(System.out::println);
Enter fullscreen mode Exit fullscreen mode

That's all for now. Maybe in the next post I'll do more with streams and other data structures. ArrayLists for sure. 👨🏽‍💻

Top comments (0)