Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid applied lazily Lists.transform in guava?

Tags:

java

guava

Map<String,Object> map = Maps.newHashMap();
map.put("test","123");
map.put("fuyou001","456");
map.put("id",145);
List<Map<String,Object>> list = Lists.newArrayList();
list.add(map);
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);`

Console is not display "test...."

how to avoid applied lazily
I also try

List<Map<String,Object>> newList = new ArrayList<Map<String, Object>>(list.size());
Collections.copy(newList,list);

but not effect

like image 461
fuyou001 Avatar asked Nov 17 '12 09:11

fuyou001


3 Answers

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)).

like image 142
Louis Wasserman Avatar answered Oct 06 '22 00:10

Louis Wasserman


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);`
like image 24
CaTalyst.X Avatar answered Oct 05 '22 22:10

CaTalyst.X


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.).

like image 37
Frank Pavageau Avatar answered Oct 05 '22 23:10

Frank Pavageau