Java programming question

Soldato
Joined
17 Dec 2006
Posts
8,197
Is it possible to convert a HashMap, where the value is a HashSet, to an Array? Such as:

HashMap<String, HashSet<String>>

into an Array. An example would be if the key (String) was "name" and the HashSet had two String values of "joe" and "bloggs", and getting it into a String array as {"name", "joe", "bloggs"}.

Thanks :)
 
Code:
Sting[] strings = map.get("name").toArray(new String[0])

Theres one version, believe JDK 11 plus has another way of doing it which I'll type out later

Woops just saw you said the map not the set. OK slightly odd requirement, give me a bit
 
Last edited:
What java version ? The collections and streaming API's give different capabilities depending on version. If I understood correctly, something like this (java 8):

Code:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;

class Scratch {
    public static void main(String[] args) {
        final HashMap<String, HashSet<String>> source = new HashMap<>();

        source.put("name", new HashSet<>(Arrays.asList("joe", "bloggs")));
        source.put("teaf", new HashSet<>(Arrays.asList("gucci", "belt", "letterbox")));

        final List<String> result = new ArrayList<>();
        source.forEach((x,y) -> {
            result.add(x);
            result.addAll(y);
        });

        result.forEach(System.out::println);
    }
}

(edit - minor tidys)
 
Last edited:
^ Just beat me to it :D, almost the same too. Plus need the extra step of getting it to an array

Code:
public static void main(String[] args) throws Exception {
    Map<String, HashSet<String>> mapToConvert = new HashMap<>();
    mapToConvert.put("name", new HashSet<>(Arrays.asList("joe", "bloggs")));
 
    List<String> entryStrings = new ArrayList<>();
    mapToConvert.forEach((k,v) -> {
        entryStrings.add(k);
        entryStrings.addAll(v);
    });
 
    String[] convertedArray = entryStrings.toArray(new String[0]);

    for(String s :convertedArray) {
        System.out.println(s);
    }
}

This line

Code:
    String[] convertedArray = entryStrings.toArray(new String[0]);

Can be this in JDK11+

Code:
    String[] convertedArray = entryStrings.toArray(String[]::new);
 
Last edited:
That's awesome, thanks a lot guys - interesting to see how you both wrote it slightly differently, and the differences between 8 and 11.
 
All the cool kids have moved off Java 8 but I work in a fairly conservative market sector (Telecoms) so we're not there yet. Whilst there's lots of useful stuff in later Java versions, none of them are in the "must have" category for us and some could cause real pain (such as any enforced moves to the module system).
 
Back
Top Bottom