Package com.google.common.collect

com.google.common.collect 是 Google Guava 库中的一个包,它提供了 Java 标准库中没有的强大和灵活的集合框架工具。这个包中的类可以帮助你处理集合,包括对集合进行转换、过滤、映射、收集等操作,以及对集合进行并发控制等。
以下是一些常用的 com.google.common.collect 包中的类:

  1. Multimap:一个将键映射到多个值的集合。它是一个映射,但允许一个键映射到多个值。
  2. Multiset:类似于 Set,但允许重复的元素。它维护元素的数量,并允许你查询特定元素的出现次数。
  3. Table:一个二维的表格数据结构,可以看作是行和列的集合。
  4. ListenableFuture:表示异步计算的结果。它是一种异步编程模型,可以让你在等待计算结果的同时执行其他任务。
  5. TreeTraverser:用于遍历树结构的工具。你可以使用它来递归地遍历一个树结构,并对每个节点执行特定的操作。
    此外,com.google.common.collect 还提供了其他一些实用的工具类和方法,可以帮助你更方便地处理集合相关的操作。这个包中的类和工具可以大大简化集合处理的代码,并提供更强大和灵活的功能。使用 com.google.common.collect 包中的工具类和方法可以极大地提高你的编程效率,并且使你的代码更加简洁和易于维护。以下是一些使用 com.google.common.collect 包中的类的示例:

示例 1: 使用 Multimap

Multimap<String, Integer> multimap = ArrayListMultimap.create();
multimap.put("One", 1);
multimap.put("One", 2);
multimap.put("Two", 3);
// 使用 forEach 方法遍历 multimap
multimap.forEach((key, value) -> System.out.println(key + ": " + value));

示例 2: 使用 Multiset

Multiset<String> multiset = TreeMultiset.create();
multiset.add("apple", 3);
multiset.add("banana", 2);
multiset.add("apple", 1);
// 查询特定元素的出现次数
int appleCount = multiset.count("apple");
System.out.println("apple count: " + appleCount);

示例 3: 使用 Table

Table<Integer, String, Integer> table = TreeBasedTable.create();
table.put(1, "One", 1);
table.put(2, "One", 2);
table.put(3, "Two", 3);
// 使用 row 和 column 方法获取特定行或列的值
List<Integer> valuesForRowOne = table.row(1).values();
List<Integer> valuesForColumnTwo = table.column("One").values();

这些示例只是 com.google.common.collect 包中的一些简单用法。你可以根据你的需求深入了解和使用这个包中的其他类和方法,以简化你的集合处理代码,并提高你的编程效率。### 示例 4: 使用 ListenableFuture

ListenableFuture<String> future = MoreExecutors.listeningDecorator(Executors.newSingleThreadExecutor())
        .submit(() -> {
            // 模拟长时间运行的任务
            Thread.sleep(1000);
            return "Result";
        });
// 添加一个 Future 监听器,当任务完成时执行特定的操作
future.addListener(() -> {
    try {
        String result = future.get(); // 获取任务结果
        System.out.println("Task result: " + result);
    } catch (Exception e) {
        e.printStackTrace();
    }
}, Executors.newSingleThreadExecutor());

示例 5: 使用 TreeTraverser

TreeTraverser<Integer> traverser = TreeTraverser.using(new Function<Integer, Set<Integer>>() {
    @Override
    public Set<Integer> apply(Integer input) {
        return Collections.singleton(input);
    }
});
// 使用 traverse 方法遍历树结构
Set<Set<Integer>> nodeSet = traverser.breadthFirstTraversal(1).transform(Collections::singleton);
nodeSet.forEach(System.out::println); // 输出每个节点集合,这里会输出 {1} 和 {2}(假设树结构为 1->2)

这些示例展示了 com.google.common.collect 包中的一些常用类和方法。通过使用这些工具类和方法,你可以更轻松地处理集合相关的操作,并提高你的代码质量和效率。
This package contains generic collection interfaces and implementations, and other utilities for working with collections.

See:
Description

Interface Summary
BiMap<K,V> A bimap (or “bidirectional map”) is a map that preserves the uniqueness of its values as well as that of its keys.
ClassToInstanceMap A map, each entry of which maps a Java raw type to an instance of that type.
Constraint A constraint that an element must satisfy in order to be added to a collection.
Interner Provides equivalent behavior to String.intern() for other immutable types.
ListMultimap<K,V> A Multimap that can hold duplicate key-value pairs and that maintains the insertion ordering of values for a given key.
MapConstraint<K,V> A constraint on the keys and values that may be added to a Map or Multimap.
MapDifference<K,V> An object representing the differences between two maps.
MapDifference.ValueDifference A difference between the mappings from two maps with the same key.
MapEvictionListener<K,V> Deprecated. use MapMaker.RemovalListener This class is scheduled for deletion from Guava in Guava release 11.0.
Maps.EntryTransformer<K,V1,V2> A transformation of the value of a key-value pair, using both key and value as inputs.
Multimap<K,V> A collection similar to a Map, but which may associate multiple values with a single key.
Multiset A collection that supports order-independent equality, like Set, but may have duplicate elements.
Multiset.Entry An unmodifiable element-count pair for a multiset.
PeekingIterator An iterator that supports a one-element lookahead while iterating.
RowSortedTable<R,C,V> Interface that extends Table and whose rows are sorted.
SetMultimap<K,V> A Multimap that cannot hold duplicate key-value pairs.
SortedMapDifference<K,V> An object representing the differences between two sorted maps.
在这里插入图片描述

package com.shanzhu.tourism.utils.recommend; import cn.hutool.core.collection.CollUtil; import cn.hutool.core.map.MapUtil; import com.google.common.collect.Lists; import com.shanzhu.tourism.utils.recommend.dto.RelateDTO; import java.util.*; import java.util.stream.Collectors; import java.util.stream.IntStream; /** * 推荐算法 * * @author: ShanZhu * @date: 2024-07-25 */ public class CoreMath { /** * 推荐计算 */ public List<String> recommend(String userId, List<RelateDTO> list) { //找到最近邻用户id Map<Double, String> distances = computeNearestNeighbor(userId, list); if(MapUtil.isEmpty(distances)){ return Collections.EMPTY_LIST; } //取出相似度最近的用户id String nearest = distances.values().iterator().next(); Iterator<String> iterator = distances.values().iterator(); while (iterator.hasNext()) { nearest = iterator.next(); } Map<String, List<RelateDTO>> userMap = list.stream().collect(Collectors.groupingBy(RelateDTO::getUserId)); //最近邻用户涉及的业务id列表 List<String> neighborItemList = userMap.get(nearest).stream().map(e -> e.getProductId()).collect(Collectors.toList()); //当前用户涉及的业务id列表 List<String> userItemList = userMap.get(userId).stream().map(e -> e.getProductId()).collect(Collectors.toList()); //找到最近邻买过,但是该用户没涉及过的,计算推荐,放入推荐列表 List<String> recommendList = new ArrayList<>(); for (String item : neighborItemList) { if (!userItemList.contains(item)) { recommendList.add(item); } } Collections.sort(recommendList); return recommendList; } /** * 在给定userId的情况下,计算其他用户和它的相关系数并排序 */ private Map<Double, String> computeNearestNeighbor(String userId, List<RelateDTO> list) { //对同一个用户id数据,做分组 Map<String, List<RelateDTO>> userMap = list.stream().collect(Collectors.groupingBy(RelateDTO::getUserId)); //treemap是从小到大排好序的
最新发布
04-03
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bol5261

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值