Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to apply a function to a collection using Java Guava?

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.

like image 261
Garrett Hall Avatar asked Sep 16 '11 15:09

Garrett Hall


People also ask

What is the use of Guava Library in Java?

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.

What is the use of Google guava dependency?

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.


2 Answers

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.

like image 110
Sean Patrick Floyd Avatar answered Nov 04 '22 05:11

Sean Patrick Floyd


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);
}
like image 23
Garrett Hall Avatar answered Nov 04 '22 03:11

Garrett Hall