Quick actions

cmd+k|ctrl+k

Navigation

Languages

Streamサンプル

Snippet info

Language

Java

Visibility

public

Author

s.ohya.3d

Created

2023-11-27T04:11:16.811695Z

Updated

2023-11-27T04:43:20.43327Z

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {

    static class Person {
        private String name;
        private int age;

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

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

        public String toString() {
            return String.format("name=%s,age=%d", this.name, this.age);
        }
    }

    public static List<Person> getData() {
        List<Person> personList = new ArrayList<>();
        personList.add(new Person("Alice", 25));
        personList.add(new Person("Bob", 30));
        personList.add(new Person("Charlie", 35));
        personList.add(new Person("Dave", 35));
        return personList;
    }

    public static void main(String[] args) {
        var personList = getData();

        // nameを取り出し
        List<String> upperCaseNames = personList.stream()
                .map(person -> person.getName().toUpperCase())
                .collect(Collectors.toList());
        System.out.println("* map result1");
        System.out.println(String.join(",", upperCaseNames));

        // nameを取り出し
        List<String> names = personList.stream()
                .map(Person::getName)
                .collect(Collectors.toList());
        System.out.println("* map result2");
        System.out.println(String.join(",", names));

        // Filter処理
        List<Person> filteredList = personList.stream()
                .filter(person -> person.getAge() >= 30)
                .collect(Collectors.toList());

        System.out.println("* filter result");
        filteredList.forEach(it -> {
            System.out.println(it);
        });

        // Group by 処理
        Map<Integer, Long> ageCount = personList.stream()
                .collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));
        System.out.println("* group-by result");
        ageCount.keySet().stream().forEach(key -> {
            System.out.printf("%s = %s\n", key, ageCount.get(key));
        });
    }
}
INFO