Search code examples
javaguava

how to transform Map<String,String> to List<String> using google collections


I have a map with strings, I want to transform it to a list of strings with " " as a key value separator. Is it possible using google collections?

Code example that I want to do using google collections:

public static List<String> addLstOfSetEnvVariables(Map<String, String> env)
{
    ArrayList<String> result = Lists.newArrayList();
    for (Entry<String, String> entry : env.entrySet())
    {
        result.add(entry.getKey() + " " + entry.getValue());
    }
    return result;
}

Solution

  • Here you go:

    private static final Joiner JOINER = Joiner.on(' ');
    public List<String> mapToList(final Map<String, String> input){
        return Lists.newArrayList(
            Iterables.transform(
                input.entrySet(), new Function<Map.Entry<String, String>, String>(){
                    @Override
                    public String apply(final Map.Entry<String, String> input){
                        return JOINER.join(input.getKey(), input.getValue());
                    }
                }));
    }
    

    Update: optimized code. Using a Joiner constant should be much faster than String.concat()


    These days, I would of course do this with Java 8 streams. No external lib needed.

    public List<String> mapToList(final Map<String, String> input) {
        return input.entrySet()
                    .stream()
                    .map(e -> new StringBuilder(
                                 e.getKey().length()
                                         + e.getValue().length()
                                         + 1
                         ).append(e.getKey())
                          .append(' ')
                          .append(e.getValue())
                          .toString()
                    )
                    .collect(Collectors.toList());
    }