Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

155
Visualizações
How to reduce list to map with Java functional API

I want to transform a string of text to a dictionary, which contains all the unique words as a key, and translation as a value.

I know how to transform a String into a stream containing unique words (Split -> List -> stream() -> distinct()), and I have translation service available, but what is the most convenient way to reduce the stream into Map with the original element and it's translation in general?

about 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

You can directly do that via collect:

yourDistinctStringStream
.collect(Collectors.toMap(
    Function.identity(), yourTranslatorService::translate
);

This returns a Map<String, String> where the map key is the original string and the map value would be the translation.

about 4 years ago · Santiago Trujillo Relatório

0

Suppose you have a list of strings "word1", "word2", "wordN" with no repetitions:

This should solve the the problem

List<String> list = Arrays.asList("word1", "word2", "workdN");
    
Map<String, String> collect = list.stream()
   .collect(Collectors.toMap(s -> s, s -> translationService(s)));

This will return, the insertion order is not maintained.

{wordN=translationN, word2=translation2, word1=translation1}

about 4 years ago · Santiago Trujillo Relatório

0

Try the following code:

public static void main(String[] args) {
    String text = "hello world java stream stream";

    Map<String, String> result = new HashSet<String>(Arrays.asList(text.split(" "))).stream().collect(Collectors.toMap(word -> word, word -> translate(word)));

    System.out.println(result);
}

private static String translate(String word) {
    return "T-" + word;
}

Will give you output:

{java=T-java, world=T-world, stream=T-stream, hello=T-hello}

about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda