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
Here you go:
private static final Joiner JOINER = Joiner.on(' ');
public List mapToList(final Map input){
return Lists.newArrayList(
Iterables.transform(
input.entrySet(), new Function, String>(){
@Override
public String apply(final Map.Entry 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 mapToList(final Map 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());
}