Dev/Java

[Java 8+] Stream to map 및 Method Reference

pu3vig 2022. 8. 8. 08:52
728x90
  • target:  String[] to Stream & Stream에서 Map으로 변환, 그리고 Method Reference

 


  • method: 

1. String[][] to Stream

2차원 String 배열을 Stream으로 변환 시, Stream.of() 또는 Arrays.stream()을 통해 Stream을 생성

// String[][] to Stream
String[][] vehicle = new String[][] {{"CAR", "Audi"}, {"BIKE", "Harley Davidson"}};
Stream<String[]> stream = Stream.of(vehicle);

* 2차원 String 배열을 순차적으로 가져오기 위해서 Stream으로 변환

* Stream의 첫번째 요소는 String[0], 두번째 요소는 String[1]과 동일

 


2. Stream to Map

위와 같이 Stream을 생성하거나, 다른 타입에서 Stream을 생성하는 경우 아래와 같이 Map으로 변경 가능

// String[][] to Stream
String[][] vehicle = new String[][] {{"CAR", "Audi"}, {"BIKE", "Harley Davidson"}};
Stream<String[]> stream = Stream.of(vehicle);

// Stream<String[]> -> Map<String, Object>
Map<String,Object> map = stream.collect(Collectors.toMap(	// 람다식 표현
							e -> (String)e[0],
							e -> (String)e[1]));

 


3. Method Reference[Java 8+]

참고로 Java 8+ 에서는 Method 참조를 통해서 아래와 같이 구현 가능

// Map to Stream
Map<String, Object> vehicle = new HashMap<String, Object>();
vehicle.put("CAR", "Audi");
vehicle.put("BIKE", "Bugatti");

// set to Stream
String<Map.Entry<String, Object>> stream = vehicle.entrySet().stream();

// stream으로부터 CAR 정보만 별도의 맵으로 생성
Map<String, Object> map = stream.filter(e -> "CAR".equals(e.getKey()))
				.collect(Collectors.toMap(  // 메소드 참조(Java 8+)를 통해 키/값 호출
                					  Map.Entry::getKey
                					, Map.Entry::getValue));

 


  • add: 

1. 변경 불가 맵 생성

Map<String, String> map = stream.collect(Collectors.collectingAndThen(
					Collectors.toMap(Map.Entry::getKey, Map.Entry:getValue)
					, Collections::<String, Object>unmodifiableMap));

 


2. 중복 키와 관련된 값 간의 충돌

Map<String, Object> map = stream.collect(Collectors.toMap(
							e -> e.getKey()
							, e -> e.getValue()
							, (oldValue, newValue) -> newValue);

 


  • source:

https://www.techiedelight.com/ko/convert-stream-to-map-java-8/

 

Java 8 이상에서 스트림을 맵으로 변환

이 게시물은 Java에서 스트림을 맵으로 변환하는 방법에 대해 설명합니다. 1. 변환 Stream 의 String[] Java 8 스트림을 사용하여 다음과 같은 정적 팩토리 메소드에서 스트림을 얻어 맵을 구성할 수 있

www.techiedelight.com

728x90