Java Stream Basic

スポンサーリンク

Stream

Stream supports collection operations for Java.

Collection codes become simple and easy to write.

Basic API

In this article, I will explain basic parts. There are several APIs, please check Oracle Page

(Stream Interface)

This is the list to support API in this article.

Operation NameWhat operation function is requiredWhat it does
filterT -> booleanReturn elements only true return
mapT -> UMap from T to U
sort(T, T) -> intSort according to function
flatmapT -> Stream<U>Return new Stream from T
reduceT -> xReturn one result

Examples

Let’s show example

filter

public void filterTest() {

        List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        list.stream()
                .filter(i -> i % 2 ==0)
                .forEach(i -> System.out.println(i)); // Only  i % 2 == 0

        Stream<Integer> stream = list.stream()
                .filter(i -> i % 2 ==0);

        list.stream()
                .filter(i -> i % 2 ==0)
                .forEach(System.out::println); // Only  i % 2 == 0
}

This example shows even number from list. 1st and 3rd one print, 2nd is return stream

I show 3 types of example.

forEach is loop function and get element one by one

filter returns only return true lambda function

map

public void mapTest() {
        List<String> list = Arrays.asList("B", "A", "I", "O", "H", "A", "Z", "A", "R", "D");

        list.stream()
                .map(s -> s.toLowerCase())
                .forEach(System.out::println);

        // mapToInt
        List<String> strInts = Arrays.asList("1", "5", "100", "1000", "501");

        strInts.stream()
                .mapToInt(Integer::parseInt)
                .forEach(i -> System.out.println(i));

        // mapToObject
        List<String> jpcoins = Arrays.asList("1", "5", "10", "100", "50", "100");
        jpcoins.stream()
                .mapToInt(Integer::parseInt)
                .mapToObj(i -> i + "yen coin")
                .forEach(System.out::print);
}

map creates new stream from original data

1st example is apply toLowerCase to each element. 2nd is parseInt 3rd example is to apply parseInt first and convert int number to format string.

sort

public void sortTest() {
        List<String> list = Arrays.asList("B", "A", "I", "O", "H", "A", "Z", "A", "R", "D");

        list.stream()
                .sorted()
                .forEach(s -> System.out.println(s));

        // Create custom sort functions
        List<String> strList = Arrays.asList("abc", "objse", "soijier", "sd", "san");
        strList.stream()
                .sorted((s1, s2) -> {
                    if (s1.length() > s2.length()) return 1;
                    else if (s1.length() < s2.length()) return -1;
                    else return 0;
                })
                .forEach(System.out::println);
}

sort operation does sort in the collection. No argument use is just sort by default primitive type order, 2nd example is custom sort function to apply (soft by string length)

flatmap

class Bands {

        private String master;

        private List<String> members = new ArrayList<>();

        public void addMember(String member) {
            members.add(member);
        }

        public Bands(String master) {
            this.master = master;
        }
}


public void flatmapTest() {
        Bands band1 = new Bands("Lucky");
        band1.addMember("Cookie");
        band1.addMember("Monja");
        band1.addMember("Tamagoyaki");

        Bands band2 = new Bands("Bubble Max");
        band2.addMember("Dankai Otoko");
        band2.addMember("Hyogoki Samezo");
        band2.addMember("Reman Haneko");

        Arrays.asList(band1, band2)
                .stream()
                .flatMap(s -> s.members.stream())
                .forEach(System.out::println);
}

flatmap create new stream from element.

In this example. There are 2 instance of Bands. Each bands has member list and new stream has all members list. One Band instance create all member list.

Final result shows all member’s name

reduce

class Kid {

        private int age;

        private String name;

        public Kid(int age, String name) {
            this.age = age;
            this.name = name;
        }

        @Override
        public String toString() {
            return String.format("Name %s, Age: %d", name, age);
        }
}

public void reduceTest() {
        List<Kid> people =
        Arrays.asList(new Kid(5, "Shinnosuke"), new Kid(11, "Konan"), new Kid(15, "Hanamichi"), new Kid(10, "Nobita"));

        people.stream()
                .reduce((p1, p2) -> p1.age > p2.age ? p1 : p2)
                .ifPresent(i -> System.out.println(i));
}

public void reduceCalcTest() {
        IntStream stream = Arrays.stream(new int[]{100, 88, 43, 35, 97, 56, 78, 80, 23});
        // ave
        stream.average().ifPresent(i -> System.out.println(i));

        // sum
        IntStream stream2 = Arrays.stream(new int[]{100, 88, 43, 35, 97, 56, 78, 80, 23});
        System.out.println(stream2.sum());

        // max, min
        IntStream stream3 = Arrays.stream(new int[]{100, 88, 43, 35, 97, 56, 78, 80, 23});
        stream3.max().ifPresent(i -> System.out.println(i));
}

This example has 2 types of reduce. reduce original idea is return one result from stream.

First example (reduceTest) is custom reduce. Return the biggest number(age) element from stream.

Second one is to use prepared reduce

ave (= average), sum (= total), max (= max) , aggregation function

Java
スポンサーリンク
Professional Programmer2

コメント