JAVA/스트림 요소 처리
[Java] 요소 변환 (매핑)
숭어싸만코
2023. 6. 21. 18:35
매핑(mapping) 이란?
- 스트림의 요소를 다른 요소로 변환하는 중간 처리 기능이다.
- 매핑 메소드는 mapXxx(), asDoubleStream(), asLongStream(), boxed(), flatMapXxx() 등이있다.
Ex) Student 스트림을 score 스트림으로 변환하고 점수를 콘솔에 출력
package study0620.Stream_Mapping;
public class Student {
private String name;
private int score;
public Student(String name, int score) {
super();
this.name = name;
this.score = score;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
}//
package study0620.Stream_Mapping;
import java.util.ArrayList;
import java.util.List;
public class MapExample {
public static void main(String[] args) {
// TODO Auto-generated method stub
// List 컬렉션 생성
List<Student> stuList = new ArrayList<Student>();
stuList.add(new Student("홍길동", 85));
stuList.add(new Student("홍길동", 92));
stuList.add(new Student("홍길동", 87));
// Student 를 score 스트림으로 변환
stuList.stream().mapToInt(t -> t.getScore()).forEach(score -> System.out.println(score));
}//
}//
Ex) 정수 스트림을 실수스트림으로 변환하고 , 기본 타입스트림을 래퍼 스트림으로 변환 하기
package study0620.Stream_Mapping;
import java.util.Arrays;
import java.util.stream.IntStream;
public class MapExample2 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = { 1, 2, 3, 4, 5 };
IntStream intStream = Arrays.stream(arr);
intStream.asDoubleStream().forEach(d -> System.out.println(d));
System.out.println();
intStream = Arrays.stream(arr);
intStream.boxed().forEach(t -> System.out.println(t.intValue()));
}//
}//