- 배열(int) -> 리스트(Integer)
// int[] -> List<Integer>
int[] arr = {1, 2, 3, 4, 5};
List<Integer> list = Arrays.stream(arr)
.boxed()
.collect(Collectors.toList());
- 리스트(Integer) -> 배열(int)
// List<Integer> -> int[]
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] arr = list.stream()
.mapToInt(Integer::intValue)
.toArray();
- List로 Map 만들기
public class Product{
public Integer num;
public String name;
}
List<Product> list = new ArrayList<>(); // 담았다 치고
Map<Integer, String> map = list.stream()
.collect(Collectors.toMap(product -> product.num, product -> product.name));
- 특정 값으로 리스트 만들기
public class Product{
public Integer num;
public String name;
}
List<Product> list = new ArrayList<>(); // 담았다 치고
List<String> nameList = list.stream()
.map(p -> p.name)
.collect(Collectors.toList());
만약, class 필드가 private이면 getter를 만들고 다음과 같이 쓴다
public class Product{
private Integer num;
private String name;
}
List<Product> list = new ArrayList<>(); // 담았다 치고
List<String> nameList = list.stream()
.map(Product::getName)
.collect(Collectors.toList());
- 특정 조건으로 데이터 필터링하기
public class Product{
private Integer num;
private String name;
}
List<Product> list = new ArrayList<>(); // 담았다 치고
List<Product> productList = list.stream()
.filter(p -> p.getNum() > 10)
.collect(Collectors.toList());