Java 8 streams - map element for a pair of elements

I have a stream of elements. I want to map each element to two different elements of the same type so that my stream is twice as long. I did this by combining the two threads, but I wonder if it is possible to do this easier? What i have done so far:

private List<String> getTranslationFilesNames() { return Stream.concat(SUPPORTED_LANGUAGES.stream() .map(lang -> PATH_TO_FILES_WITH_TRANSLATIONS_1 + lang + FILE_EXTENSION), SUPPORTED_LANGUAGES.stream() .map(lang -> PATH_TO_FILES_WITH_TRANSLATIONS_2 + lang + FILE_EXTENSION)) .collect(Collectors.toList()); } 

I do not think this solution is very elegant. Is there a better approach to achieve the same effect?

+5
source share
2 answers

If you don't need order, you can map each element to a pair of elements using flatMap :

 private List<String> getTranslationFilesNames() { return SUPPORTED_LANGUAGES.stream() .flatMap(lang -> Stream.of(PATH_TO_FILES_WITH_TRANSLATIONS_1 + lang + FILE_EXTENSION, PATH_TO_FILES_WITH_TRANSLATIONS_2 + lang + FILE_EXTENSION)), .collect(Collectors.toList()); } 
+5
source

Instead of creating a combined Stream you can simply use the #flatMap operator to duplicate input elements (note that this may be a suitable solution only if the order of the elements does not matter):

 private List<String> getTranslationFilesNames() { return SUPPORTED_LANGUAGES.stream() .flatMap(s -> Stream.of( PATH_TO_FILES_WITH_TRANSLATIONS_1 + s + FILE_EXTENSION, PATH_TO_FILES_WITH_TRANSLATIONS_2 + s + FILE_EXTENSION ) ) .collect(Collectors.toList()); } 
+4
source

Source: https://habr.com/ru/post/1272090/


All Articles