![](/img/trans.png)
[英]Is it possible to apply joiner (collector, accumulator) over function using Java Guava?
[英]Is it possible to apply a function to a collection using Java Guava?
我想使用Guava將函數應用於集合,映射等。
基本上,我需要分別調整Table
行和列的大小,以便所有行和列具有相同的大小,執行如下操作:
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
應該是什么。 但是,我需要應用它,而不僅僅是返回一個Collection
。
在Guava中,您不會轉換現有列表,而是使用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);
輸出:
[賽車,棚車]
或者,如果您不需要List
而Collection
也可以,您可以使用轉換后的實時視圖:
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();
}
});
此Collection
是底層的實時視圖,因此list
更改將反映在此Collection
。
如何創建這樣的函數:
public static <T> void apply(Iterable<T> iterable, Function<T, Void> function) {
for (T input : iterable)
function.apply(input);
}
Sean已經提到Guava不會更改原始集合,因此您無法在現有集合中“應用”某個功能。
目前還不清楚你的ResizeFunction
函數是做什么的,如果你只改變Table<Integer, Integer, Cell>
中Cell
的值,那么你可以使用Tables#transformValues()
Guava不允許您更改Table<R, C, V>
的R
和C
的值(在標准Tables
類中),因為它們在返回行或列映射時用作鍵( Table#rowMap()
和Table#columnMap()
)並且您無法轉換它們,因為所有用於轉換和過濾的Guava方法都會產生延遲結果意味着函數/謂詞僅在需要時應用,因為使用了對象。 他們不創建副本。 因此,轉換很容易打破Set的要求。
如果您仍想這樣做,那么您可以將Table
對象包裝在您自己的類中並提供所需的方法。
我認為最好在填充之前將表設置為適當的大小/具有適當數量的單元格,即使它們是空的。 就像是:
for (int i=0; i<numRows; i++)
for (int j=0; j<numColumns; j++)
table.put(i,j,null);
這將確保表中的每個位置都有一個單元格。 只要您只將單元格添加到numRows,numColumns中的行,列位置,您將保留一個“方形”表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.