예제가 포함된 Java의 스트림 map()

스트림 맵(함수 매퍼) 주어진 함수를 이 스트림의 요소에 적용한 결과로 구성된 스트림을 반환합니다.

스트림 맵(Function mapper)은 중간 작업 . 이러한 작업은 항상 게으르다. 중간 작업은 Stream 인스턴스에서 호출되고 처리가 완료된 후 Stream 인스턴스를 출력으로 제공합니다.

구문:

  < R>개울 < R>지도(기능 < ? super T , ? extends R>매퍼) 여기서 R은 새 스트림의 요소 유형입니다. Stream은 인터페이스이고 T는 스트림 요소의 유형입니다. 매퍼는 각 요소에 적용되는 무상태 함수이며 이 함수는 새 스트림을 반환합니다. 

예시 1 : 스트림의 각 요소에 대해 숫자 * 3의 연산을 수행하는 스트림 맵() 함수입니다.




// Java code for Stream map(Function mapper)> // to get a stream by applying the> // given function to this stream.> import> java.util.*;> > class> GFG {> > > // Driver code> > public> static> void> main(String[] args)> > {> > > System.out.println(> 'The stream after applying '> > +> 'the function is : '> );> > > // Creating a list of Integers> > List list = Arrays.asList(> 3> ,> 6> ,> 9> ,> 12> ,> 15> );> > > // Using Stream map(Function mapper) and> > // displaying the corresponding new stream> > list.stream().map(number ->번호 *> 3> ).forEach(System.out::println);> > }> }>

출력 :

 The stream after applying the function is : 9 18 27 36 45 

예시 2: 소문자를 대문자로 변환하는 연산을 포함하는 Stream map() 함수.




// Java code for Stream map(Function mapper)> // to get a stream by applying the> // given function to this stream.> import> java.util.*;> import> java.util.stream.Collectors;> > class> GFG {> > > // Driver code> > public> static> void> main(String[] args)> > {> > > System.out.println(> 'The stream after applying '> > +> 'the function is : '> );> > > // Creating a list of Integers> > List list = Arrays.asList(> 'geeks'> ,> 'gfg'> ,> 'g'> ,> > 'e'> ,> 'e'> ,> 'k'> ,> 's'> );> > > // Using Stream map(Function mapper) to> > // convert the Strings in stream to> > // UpperCase form> > List answer = list.stream().map(String::toUpperCase).> > collect(Collectors.toList());> > > // displaying the new stream of UpperCase Strings> > System.out.println(answer);> > }> }>

출력 :

 The stream after applying the function is : [GEEKS, GFG, G, E, E, K, S] 

예시 3: 문자열 대신 문자열 길이를 매핑하는 작업을 포함하는 스트림 map() 함수입니다.




// Java code for Stream map(Function mapper)> // to get a stream by applying the> // given function to this stream.> import> java.util.*;> > class> GFG {> > > // Driver code> > public> static> void> main(String[] args)> > {> > > System.out.println(> 'The stream after applying '> > +> 'the function is : '> );> > > // Creating a list of Strings> > List list = Arrays.asList(> 'Geeks'> ,> 'FOR'> ,> 'GEEKSQUIZ'> ,> > 'Computer'> ,> 'Science'> ,> 'gfg'> );> > > // Using Stream map(Function mapper) and> > // displaying the length of each String> > list.stream().map(str ->str.length()).forEach(System.out::println);> > }> }>

출력 :

 The stream after applying the function is : 5 3 9 8 7 3