JUMBO
JUMBO

Reputation: 29

Java stream modifying strings

I want to ask you guys for help in modyfing my list of strings using fp. Im new to stream api, have some basic knowledge but can't resolve this task. I have three list of strings, each of them contain title of movie in my origin language and translation in English, then every list of strings go to map. I want to reach the outcome that I print movies from list separated with '>' and then when it switches to another list I want to place '|'. For example: Zelazny czlowiek>IronMan|Msciciele>Avengers|Blyskawica>Flash

   public Map<String, List<String>> getMovies() {
    List<String> ironManTranslations = new ArrayList<>();
    ironManTranslations.add("Żelazny Człowiek");
    ironManTranslations.add("Iron Man");

    List<String> avengersTranslations = new ArrayList<>();
    avengersTranslations.add("Mściciele");
    avengersTranslations.add("Avengers");

    List<String> flashTranslations = new ArrayList<>();
    flashTranslations.add("Błyskawica");
    flashTranslations.add("Flash");

    Map<String, List<String>> booksTitlesWithTranslations = new HashMap<>();
    booksTitlesWithTranslations.put("IM", ironManTranslations);
    booksTitlesWithTranslations.put("AV", avengersTranslations);
    booksTitlesWithTranslations.put("FL", flashTranslations);

    return booksTitlesWithTranslations;
}

public void printMovies(){

    getMovies().values().stream().flatMap(movie -> movie.stream().map(s -> s + ">")).forEach(System.out::print);

}

Upvotes: 0

Views: 245

Answers (1)

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

You can use the map operator to create a translation pair for each list. And then use joining collector to join them between the lists using the | operator. Here's how it looks.

String mStr = booksTitlesWithTranslations.values().stream()
    .map(l -> l.get(0) + ">" + l.get(1))
    .collect(Collectors.joining("|"));

Upvotes: 1

Related Questions