잭 러셀 :
나는 구문이 몇 가지 간단한 JSON 파일이
"key1": "value1"
"key2": "value2"
기타
나는 그들 각각의에서지도를 만든 다음 하나에 병합해야합니다. 다음 코드로 예상되는 작품 :
private TranslationBundle assembleBundle(List<String> translations) {
TranslationBundle translationBundle = new TranslationBundle();
Map<String, String> bundledTranslationMap = new HashMap<>();
translations.forEach(translation -> {
bundledTranslationMap.putAll(getSingleTranslationMap(translation).);
});
translationBundle.setTranslationMap(bundledTranslationMap);
return translationBundle;
}
private Map<String, String> getSingleTranslationMap(String translation){
ObjectMapper mapper = new ObjectMapper();
try{
return mapper.readValue(translation, new TypeReference<Map<String, String>>(){});
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
내가 달성하고자하는 것은에서 코드를 재 작성하는 assembleBundle
등의 좀 더 기능 하나에 방법을
translations.stream().
map(this::getSingleTranslationMap)
.collect(collect to single HashMap);
에서 collect()
방법, 지금까지의 내가 아는 한, 나는 어떻게 든 각각의 결과를 키와 값에 액세스 할 수 있습니다 getSingleTranslationMap
. 이 방법의 결과에 할당 된 변수 이름이 없기 때문에, 어떻게이 수행해야? 어쩌면 내가 전혀 잘못된 접근 방식을 시도하고있다?
그들은했다 :
당신은 개별 변환 할 수 있습니다 Map
에 의해 반환의 getSingleTranslationMap
으로 Stream
맵 항목을 단일로 수집 Map
:
Map<String, String> bundledTranslationMap =
translations.stream()
.flatMap(translation -> getSingleTranslationMap(translation).entrySet()
.stream())
.collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));
물론, 경우 getSingleTranslationMap
반환 Map
하나와 함께 Entry
, 그것은 그 방법에 대한 더 적합 할 수 있습니다는 돌아갑니다 Map.Entry
대신 Map
위의 단순화 것이다, Stream
파이프 라인을.
중복 키가 가능한 경우 PS는, 당신은에 병합 기능을 추가해야합니다 toMap()
전화.