Skip to content

Instantly share code, notes, and snippets.

@trevershick
Created October 16, 2013 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trevershick/7008154 to your computer and use it in GitHub Desktop.
Save trevershick/7008154 to your computer and use it in GitHub Desktop.
Sample code showing how even after a Guava transform, the underlying collection may still be altered.
import static com.google.common.collect.Collections2.transform;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
public class WatchMe {
public static void main(String[] args) {
Set<Noisy> s1 = Sets.newHashSet();
Set<Noisy> s2 = Sets.newHashSet();
s1.add(new Noisy("n1"));
s1.add(new Noisy("n2"));
s1.add(new Noisy("n3"));
s1.add(new Noisy("n4"));
s1.add(new Noisy("n5"));
s2.add(new Noisy("n2"));
s2.add(new Noisy("n3"));
s2.add(new Noisy("n4"));
System.out.println("Set 1:" + s1);
System.out.println("Set 2:" + s2);
Collection<String> xformed1 = transform(s1, new Function<Noisy,String>() {
public String apply(Noisy input) {
return input.humanValue();
}});
Collection<String> xformed2 = transform(s2, new Function<Noisy,String>() {
public String apply(Noisy input) {
return input.humanValue();
}});
System.out.println("X-Formed 1:" + xformed1);
System.out.println("X-Formed 2:" + xformed2);
System.out.println(" ** Call xformed1.retainAll(xformed2)");
xformed1.retainAll(xformed2);
System.out.println("X-Formed 1 after retainAll(xformed2):" + xformed1);
System.out.println("Set 1 after xformed1.retainAll(xformed2):" + s1);
System.out.println("\n\nMy initial though was that xformed1 would be altered to filter out");
System.out.println("the contents of xformed 2 but what's occurring is that the UNDERLYING");
System.out.println("Set is actually being altered. ");
}
}
Set 1:[n2, n1, n4, n3, n5]
Set 2:[n2, n4, n3]
X-Formed 1:[The value = n2, The value = n1, The value = n4, The value = n3, The value = n5]
X-Formed 2:[The value = n2, The value = n4, The value = n3]
** Call xformed1.retainAll(xformed2)
X-Formed 1 after retainAll(xformed2):[The value = n2, The value = n4, The value = n3]
Set 1 after xformed1.retainAll(xformed2):[n2, n4, n3]
My initial though was that xformed1 would be altered to filter out
the contents of xformed 2 but what's occurring is that the UNDERLYING
Set is actually being altered.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment