是否可以使用Java Guava对集合应用函数? [英] Is it possible to apply a function to a collection using Java Guava?

查看:215
本文介绍了是否可以使用Java Guava对集合应用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用Guava将一个函数应用到集合,映射等。

I want to apply a function to a collection, map, etc, using Guava.

基本上,我需要调整 Table ,所以所有行和列的大小相同,这样做:

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);
}



我已经知道 ResizeFunction 应该是。但是,我需要应用,而不只是返回集合

I already have an idea of what the ResizeFunction should be. However, I need to apply it, not just return a Collection.

推荐答案

在Guava中,不会转换现有列表,而是使用Iterables.transform创建一个新的列表:

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

输出:


[racecar,boxcar]

[racecar, boxcar]

或者,如果您不需要 c $ c>和 Collection 将可以使用转换后的实时视图:

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.

这篇关于是否可以使用Java Guava对集合应用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆