스트림 API의 map과 flatMap 메서드는 특정 데이터를 선택 가능하게 기능을 제공.

 

스트림 map

List<Game> games = Arrays.asList(
	new Game("CALL 1", 20000)
	, new Game("DIA 1", 30000)
	, new Game("DIA 2", 40000)
	, new Game("DIA 3", 50000)
);

객체 데이터를 생성 후에 간단하게 리스트 요소들의 게임명을 가져오는 map에 예제.

List<String> gameNameList = games.stream()
				.map(Game::getName)
				.collect(toList());
		
gameNameList.stream().forEach(name -> System.out.println(name));

만약에 각 요소들의 게임명의 길이가 필요하다면 아래와 같이 체이닝 처리할 수 있다.

List<Integer> gameNameLengthList = games.stream()
				.map(Game::getName)
				.map(String::length)
				.collect(toList());
		
gameNameLengthList.stream().forEach(itemLength -> System.out.println(itemLength));

 

결과값

6
5
5
5

 

스트림 flatMap

메서드 map을 이용해 리스트의 중복을 제거한 각 단어의 길이를 반환한다고 하자.

아래와 같이 작성한다면 리턴 값은 Stream<String[]>이 된다.

각각의 스트림으로 반환이 되는 것이다.

List <String> words = Arrays.asList("Goodbye", "World");
		
List<String[]> uniqueCharList = words.stream()
.map(word -> word.split(""))
.distinct()
.collect(toList());

하나의 스트림으로 반환하고 싶다면 어떻게 해야 할까?

아래와 같이 작성해도 결국 Stream 리스트가 반환된다.

 

List<Stream<String>> uniqueCharList = words.stream()
		.map(word -> word.split(""))
		.map(Arrays::stream)
		.distinct()
		.collect(toList());​

flatMap을 사용하면 각 배열을 스트림이 아니라 스트림의 콘텐츠로 맵핑한다.

앞의 예제와는 다르게 하나의 스트림을 반환한다.

List<String> uniqueCharList = words.stream()
		.map(word -> word.split(""))
		.flatMap(stream -> Arrays.stream(stream))
		.distinct()
		.collect(toList());
		
uniqueCharList.stream().forEach(System.out::println);

 

결과값

GodbyeWrl

 

'Java > Stream' 카테고리의 다른 글

기본형 특화 스트림  (0) 2022.10.27
리듀싱  (0) 2022.10.26
검색과 매칭  (0) 2022.10.26
필터링 및 슬라이싱  (0) 2022.10.10
정의 및 특징  (0) 2022.10.03

+ Recent posts