如何在Java8中将列表转换为HashBasedTable?
当前代码如下:
import org.glassfish.jersey.internal.guava.HashBasedTable;
import org.glassfish.jersey.internal.guava.Table;
List<ApplicationUsage> appUsageFromDB = computerDao.findAllCompAppUsages(new HashSet<>(currentBatch));
Table<String, String, Integer> table = HashBasedTable.create();
for(ApplicationUsage au: appUsageFromDB) {
table.put(au.getId(), au.getName(), au);
}我需要将组合键存储在其中,稍后再获取相同的组合键。
发布于 2020-02-11 18:56:42
如果这些内部至少是guava-21,您可以通过它们自己的收集器来完成,但我不认为您使用简单的循环所做的事情有任何问题。
Table<String, String, ApplicationUsage> result =
appUsageFromDB.stream()
.collect(ImmutableTable.toImmutableTable(
ApplicationUsage::getId,
ApplicationUsage::getName,
Function.identity()
));发布于 2020-02-11 19:41:22
首先,您不应该依赖内部包,只需显式地将Guava添加到您的项目中即可。你可以使用Tables#toTable收集器,如果你想要可变的表作为结果,否则@Eugene的答案中给出的不可变的表就很好了:
import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;
import com.google.common.collect.Tables;
// ...
Table<String, String, ApplicationUsage> table2 = appUsageFromDB.stream()
.collect(Tables.toTable(
ApplicationUsage::getId,
ApplicationUsage::getName,
au -> au,
HashBasedTable::create
));此外,您的代码不能编译,因为它期望Integer作为表值,但是您在循环中添加了ApplicationUsage。如果需要,相应地更改表收集器中的类型和第三个参数。
https://stackoverflow.com/questions/60165842
复制相似问题