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

227
Visualizações
Convert a set to map in java

I have a set and I want to convert it to map in order to use it later in guava's Maps.difference(). I only care about the keys in the difference.
Came up with this version:

private <T> Map<T, T> toMap(Set<T> set) {
  return set.stream().collect(Collectors.toMap(Function.identity(), Function.identity()));
}

However, I know that usually, a set has a backing field of map. This is the method I use to create the map:

public static <E> Set<E> newConcurrentHashSet() {
  return Collections.newSetFromMap(new ConcurrentHashMap<E, Boolean>());
}

Since I only need the keys I thought maybe I can get a view of this field somehow. any idea?

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

0

I ended up with a fairly straight-forward one line solution with Java 8 as follows:

Map<String, Foo> map = fooSet.stream().collect(Collectors.toMap(Foo::getKey, e -> e));
  • fooSet is a set of objects of type Foo, i.e. Set<Foo> fooSet
  • Foo has a getter called getKey which returns a String
about 4 years ago · Santiago Trujillo Relatório

0

You can convert a Set to a Map (same key and value taken from elements of Set) as shown below:

private <T> Map<T, T> toMap(Set<T> set) {
    Map<T, T> map = new ConcurrentHashMap<>();
    set.forEach(t -> map.put(t, t));//contains same key and value pair
    return map;
}
about 4 years ago · Santiago Trujillo Relatório

0

Improvement of developer's answer:

Map<String, Foo> map = fooSet.stream().collect(Collectors.toMap(Foo::getKey, Function.identity()));

or if you statically import Collectors.toMap and Function.identity:

Map<String, Foo> map = fooSet.stream().collect(toMap(Foo::getKey, identity()));
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