how to transform Map to List using google collections

后端 未结 4 2068
抹茶落季
抹茶落季 2021-02-14 02:01

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

4条回答
  •  心在旅途
    2021-02-14 02:16

    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());
    }
    

提交回复
热议问题