/** * Creates an instance by supplying a map of {@link String} the language tag and {@link String}. Changes to the map won't affect the instance. * * {@include.example io.sphere.sdk.models.LocalizedStringTest#ofStringToStringMap()} * * @param translations the key value pairs for the translation * @return a new instance which has the same key value pairs as {@code translation} at creation time */ @JsonIgnore public static LocalizedString ofStringToStringMap(final Map<String, String> translations) { requireNonNull(translations); return translations.entrySet().stream() .map(localeEntry -> { final Locale locale = Locale.forLanguageTag(localeEntry.getKey()); return LocalizedStringEntry.of(locale, localeEntry.getValue()); }) .collect(LocalizedString.streamCollector()); }
/** * Creates a new instance where each translation value is transformed with {@code function}. * * {@include.example io.sphere.sdk.models.LocalizedStringTest#mapValue()} * * @param function transforms a value for a locale into a new value * @return a new {@link LocalizedString} which consist all elements for this transformed with {@code function} */ public LocalizedString mapValue(final BiFunction<Locale, String, String> function) { return stream().map(entry -> { final String newValue = function.apply(entry.getLocale(), entry.getValue()); return LocalizedStringEntry.of(entry.getLocale(), newValue); }).collect(streamCollector()); }
@Test public void stream() throws Exception { final LocalizedString upperCased = LocalizedString.of(Locale.GERMAN, "Hundefutter", Locale.ENGLISH, "dog food") .stream() .map(e -> LocalizedStringEntry.of(e.getLocale(), e.getValue().toUpperCase())) .collect(LocalizedString.streamCollector()); assertThat(upperCased).isEqualTo(LocalizedString.of(Locale.GERMAN, "HUNDEFUTTER", Locale.ENGLISH, "DOG FOOD")); }
@Test public void streamAndCollector() { final LocalizedString ls = LocalizedString.of(Locale.GERMAN, "Company Hundefutter", Locale.ENGLISH, "Company dog food"); final Stream<LocalizedStringEntry> stream = ls.stream(); final LocalizedString updatedLs = stream .map(entry -> { final Locale locale = entry.getLocale(); final String value = entry.getValue(); final String newValue = value.replace("Company ", ""); return LocalizedStringEntry.of(locale, newValue); }) .collect(LocalizedString.streamCollector()); assertThat(updatedLs).isEqualTo(LocalizedString.of(Locale.GERMAN, "Hundefutter", Locale.ENGLISH, "dog food")); }