How to avoid applied lazily Lists.transform in guava?

后端 未结 3 1634
死守一世寂寞
死守一世寂寞 2021-01-11 15:11
Map map = Maps.newHashMap();
map.put(\"test\",\"123\");
map.put(\"fuyou001\",\"456\");
map.put(\"id\",1         


        
相关标签:
3条回答
  • 2021-01-11 15:47

    Using an ImmutableList will force the values to be computed eagerly, and thus, no need for an extra copy afterwards. This is perhaps a more elegant solution:

    list = ImmutableList.copyOf(Lists.transform(list, 
      new Function<Map<String, Object>, Object>() {
      @Override
      public Object apply(@Nullable Map<String, Object> input) {
        System.out.println("test:" + input);
        return input;
      }
    }));
    System.out.println(list);`
    
    0 讨论(0)
  • 2021-01-11 16:07

    Functions in general should not have side effects; that's your real problem.

    That said, if you insist on applying the transformation immediately, do a copy: Lists.newArrayList(Lists.transform(list, function)).

    0 讨论(0)
  • 2021-01-11 16:10

    To complement Louis' answer, you're using Lists.transform() as if it modified the original list, like Collections.sort(). It doesn't.

    You have to use the return value of Lists.transform() to see something happen, keeping in mind that it's a view which gets evaluated each and every time you call it. So if you need to use the result several times, as Louis said, do a copy in a new List (ArrayList, ImmutableList, etc.).

    0 讨论(0)
提交回复
热议问题