반응형
import java.util.*;
import java.util.stream.*;
public class JgStream4 {
public static void main(String[] args) {
List<Pet> list = Arrays.asList(
new Pet("고양이", 2, Pet.Gender.Female),
new Pet("강아지", 5, Pet.Gender.Male),
new Pet("앵무새", 1, Pet.Gender.Female),
new Pet("햄스터", 3, Pet.Gender.Female)
);
Map<String, Integer> map = list.stream().filter(a -> a.getAge()>1 && a.getGender()==Pet.Gender.Female)
.collect(Collectors.toMap(
b->b.getKind(), b->b.getAge()
));
System.out.println(map);
}
}
//출력
{고양이=2, 햄스터=3}
class Pet {
public enum Gender {Male, Female};
private String kind;
private int age;
private Gender gender;
public Pet(String kind, int age, Gender gender) {
this.kind = kind;
this.age = age;
this.gender = gender;
}
public String getKind() {
return kind;
}
public int getAge() {
return age;
}
public Gender getGender() {
return gender;
}
}
Stream의 collect() 함수를 통해 toMap, toSet, toList 가 가능하다
반응형
'Java > Simple code' 카테고리의 다른 글
Java 제네릭(Generic) 메서드 (0) | 2023.01.23 |
---|---|
Java_제네릭(Generic) 클래스 (0) | 2023.01.23 |
Java list to stream, set to stream (0) | 2023.01.23 |
Java IntStream 생성( Array to IntStream) (0) | 2023.01.23 |
Java Array to Stream (배열 스트림 생성) (0) | 2023.01.22 |