Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

guava

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;
}
like image 353
oshai Avatar asked Feb 04 '11 06:02

oshai


People also ask

How do you convert a Map to a String?

Use Object#toString() . String string = map. toString();

How do you convert a Map key and value in a String?

Convert a Map to a String Using Java Streams To perform conversion using streams, we first need to create a stream out of the available Map keys. Second, we're mapping each key to a human-readable String.

How do I convert a list of strings to a list of objects?

Pass the List<String> as a parameter to the constructor of a new ArrayList<Object> . List<Object> objectList = new ArrayList<Object>(stringList);

Can we Map a String?

8 Answers. Show activity on this post. Then you can create a Map<String,ComputeString> object like you want in the first place. Using a map will be much faster than reflection and will also give more type-safety, so I would advise the above.


1 Answers

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());
}
like image 77
Sean Patrick Floyd Avatar answered Oct 01 '22 13:10

Sean Patrick Floyd