java - 按值查询Guava表

标签 java collections guava

我正在从 CSV 文件创建一个表,其中的数据由不同项目的用户评分 dataset 组成。

我使用以下代码来填充表格

Reader in = new FileReader(OriginalRatingDataPath);
Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);

Table<Integer,Integer,Integer> ratings = HashBasedTable.create();
for (CSVRecord record : records) {
    ratings.put(Integer.parseInt(record.get("userID")),Integer.parseInt(record.get("itemID")),Integer.parseInt(record.get("rating")));
}

如何查询表以获取对项目 3 至 5 进行评分的用户?

最佳答案

选项 1

表的要点是允许您按行或列访问记录。所以如果需要通过评级来访问,最简单的方法就是使用评级作为列。

Reader in = new FileReader(OriginalRatingDataPath);
Iterable<CSVRecord> records = CSVFormat.EXCEL.withHeader().parse(in);

Table<Integer,Integer,Integer> ratings = HashBasedTable.create();
for (CSVRecord record : records) {
    ratings.put(Integer.parseInt(record.get("userID")), Integer.parseInt(record.get("rating")), Integer.parseInt(record.get("itemID")));
}

// Copy column 3 to a new map to prevent editing the table itself
// when adding columns 4 and 5 - in turn preventing a memory leak
// from indirectly holding onto `ratings` through the map
Map<Integer, Integer> usersToItemId = new HashMap<>(ratings.column(3));
usersToItemId.putAll(ratings.column(4));
usersToItemId.putAll(ratings.column(5));

// To get just User IDs
Set<Integer> userIds = usersToItemId.keySet();

选项 2

如果您的大部分操作将通过 itemIDuserID 访问表,您可能不想对列进行评级。在这种情况下,您可以使用cellSet方法并手动迭代表。它的性能不会那么好,但它会起作用。

// Your current code

Set<Integer> userIds = new HashSet<>();
for (Table.Cell<Integer, Integer, Integer> cell : ratings.cellSet()) {
    if (3 <= cell.getValue() && cell.getValue() <= 5) {
        userIds.add(cell.getRowKey());
    }
}

关于java - 按值查询Guava表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44483754/

相关文章:

java - java.util.Arrays 如何处理 ArrayList 的排序(长度与大小)?

java - 上传前文件上传进度跳到 100%

java - Redis 缓存 Map<Integer, String>

来自 .csv 文件的 Java 工资总和

java - 对 Java 集合进行排序时忽略单词 "the"

ios - j2objc 错误添加 Guava (When.o 丢失)

java - HashMap put 还是 putAll? - java

java - 不使用证书的加密 RMI 通信

java - 按值对象属性对 LinkedHashMap 键集进行排序

java - 使用 Guava 将多个 Collections<A> 合并到一个 Collection<B> 中的单个 Collection<A>