import static java.lang.System.out;// shorter & simplified
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class Main {
static record Person(String name, int age) {// immutable
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
public static List<Person> getPeople() {// better naming
return List.of
(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 35),
new Person("Dave", 35)
);// immutable & more concise
}
public static void main(String[] args) {
var personList = getPeople();
// nameを取り出し
List<String> upperCaseNames = personList.stream()
.map(person -> person.getName().toUpperCase())
.toList();// shortened
out.println("* map result1");
out.println(String.join(",", upperCaseNames));
// nameを取り出し
List<String> names = personList.stream()
.map(Person::getName)
.toList();
out.println("* map result2");
out.println(String.join(",", names));
// Filter処理
List<Person> filteredList = personList.stream()
.filter(person -> person.getAge() >= 30)
.toList();
out.println("* filter result");
filteredList.forEach(out::println);// simplified
// Group by 処理
Map<Integer, Long> ageCount = personList.stream()
.collect(Collectors.groupingBy(Person::getAge, Collectors.counting()));
out.println("* group-by result");
ageCount.keySet().stream().forEach(key -> {
out.printf("%s = %s\n", key, ageCount.get(key));
});
}
}