java - 按类别将一个集合拆分为多个集合

标签 java split set

很抱歉,如果这个问题已在其他地方得到解答,但我还没有找到好的答案!


我有一个 Set 对象,我需要根据它们的底层 class 类型将它们拆分为每个对象的 Set(显然这意味着初始集合中的每个对象只会出现在新 Set 对象的一个中)。

我目前的做法如下:

public static Map<Class,Set<Foo>> splitByClass(Set<Foo> foos) {

    // Create a map for the result
    Map<Class,Set<Foo>> FooMap = new HashMap<Class,Set<Foo>>();

    for (Foo foo: foos) {
        Class type = foo.getClass();

        // If a set for this key exists, add the item to that.
        if (FooMap.containsKey(type)) {
            FooMap.get(type).add(foo);
        } else {
            // Otherwise make a new set, add the item and the set to the map.
            Set<Foo> set = new HashSet<Foo>();
            set.add(foo);
            FooMap.put(type, set);
        }
    }        
    return FooMap;
}

我的问题:是否有更通用的方法根据某些评估方法(例如检查类类型)将 Set 拆分为子集?

最佳答案

您可以使用 Guava Multimap ,它会让生活变得更简单:

Multimap<Class<? extends Foo>, Foo> mmap = HashMultimap.create();
for (Foo foo : foos) {
    mmap.put(foo.getClass(), foo);
}
return mmap;

除了您必须将返回类型更改为 Multimap<Class<? extends Foo>, Foo> 之外,这段代码与您上面的代码非常相似。 .

这是一个通用版本,适用于任何提供的接口(interface)类型:

public static <X> Multimap<Class<X>, X> splitByClass(
    final Iterable<? extends X> implementations, final Class<X> interfaceType) {

    final Multimap<Class<X>, X> mmap = HashMultimap.create();
    for (final X implementation : implementations) {
        @SuppressWarnings("unchecked")
        // this should be safe:
        final Class<X> implementationType = (Class<X>) implementation.getClass();
        mmap.put(implementationType, implementation);
    }
    return mmap;
}

关于java - 按类别将一个集合拆分为多个集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7498593/

相关文章:

string - 快速将字符串拆分为多行

python - 如何用括号外的逗号分割字符串?

c++ - 是否有针对大量部分拷贝优化的 C++ STL 关联数据结构版本?

Java - Set<ObjectS> removeAll(Set<Object>) 不执行其工作

wpf - 将 WPF PathGeometry 拆分为 "tiles"

java - 从 jar 文件中的文件夹中读取文件

java - 如何调整 Canvas 中位图的大小?

java - 如何在类编译后运行java程序

data-structures - golang 为什么我们没有一套数据结构

java - Gradle EBean 增强 - 实体未增强