0

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);

}

1 Answer 1

1

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("|"));
Sign up to request clarification or add additional context in comments.

3 Comments

Seems to be easy now. Thank you so much for your help, for sure I'll remember this for future tasks like this one.
The general solution for arbitrary list sizes instead of fixed two, is .map(l -> String.join(">", l))
I didn't even know that. Thanks for letting us know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.