I want to apply a function to a collection, map, etc, using Guava.
Basically, I need to resize the rows and columns of a Table separately so all rows and columns are of equal size, doing something like this:
    Table<Integer, Integer, Cell> table = HashBasedTable.create();
    Maps.transformValues(table.columnMap(), new ResizeFunction(BlockDimension.WIDTH));
    Maps.transformValues(table.rowMap(), new ResizeFunction(BlockDimension.HEIGHT));
public interface Cell {
    int getSize(BlockDimension dimension);
    void setSize(BlockDimension dimension);
}
I already have an idea of what the ResizeFunction should be.  However, I need to apply it, not just return a Collection.
Guava is an open-source “Collection Library” library for Java, developed by Google. It provides utilities for working with Java collections. As you dive deep into Guava you'll notice how it reduces coding errors, facilitates standard coding practices and boost productivity by making code concise and easy to read.
Guava is an open source, Java-based library developed by Google. It facilitates best coding practices and helps reduce coding errors. It provides utility methods for collections, caching, primitives support, concurrency, common annotations, string processing, I/O, and validations.
In Guava, you don't convert existing Lists, but instead create a new one using Iterables.transform:
final List<String> list = Arrays.asList("race", "box");
final List<String> transformed =
    Lists.newArrayList(Iterables.transform(list, new Function<String, String>() {
        @Override
        public String apply(final String input) {
            return new StringBuilder().append(input).append("car").toString();
        }
    }));
System.out.println(transformed);
Output:
[racecar, boxcar]
Or, if you don't need a List and a Collection will do, you can use a transformed live view:
final Collection<String> transformed =
    Collections2.transform(list, new Function<String, String>() {
        @Override
        public String apply(final String input) {
            return new StringBuilder().append(input).append("car").toString();
        }
    });
This Collection is a live view of the underlying one, so changes to list will be reflected in this Collection.
What about creating a function like this:
public static <T> void apply(Iterable<T> iterable, Function<T, Void> function) {
    for (T input : iterable)
        function.apply(input);
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With