java - 在Java中搜索具有不同键的对象

标签 java maps

我是一名从 C++ 过渡到 Java 的开发人员。所以我仍然不具备以 Java 方式完成工作的所有专业知识。 我有以下类(class)

class Site
{
   String siteName;
   Integer siteId;
   Integer views;
   Integer searches;
}

我维护 2 个 map 来搜索此类的对象(使用 sitename 或 siteid)

HashMap<String, Site> siteNameToSiteMap;
HashMap<Integer, Site> siteIdToSiteMap;

但是展望 future ,我必须向类 Site 中添加一个名为parentBrand 的字段。这将迫使我创建另一个 map 以便能够对其进行搜索。

HashMap<String, Site> parentBrandToSiteMap;

此类“索引”变量可能会增加前进的速度,从而也会增加我维护的 map 数量。

我记得在用 C++ 开发时解决类似问题时使用了 Boost 多索引容器。我可以使用 Java 中的同等支持良好、文档齐全的库吗?如果不是,有没有办法重构我的代码来解决我的问题。

最佳答案

令我惊讶的是,没有像 boost 多索引容器这样的版本可用。 (也许在某个地方......)但是在 Java 中连接你自己的版本并不难。

一个粗糙但有效的版本可能如下所示:

基本站点对象

我使用了一个稍微不同的 Site 对象,只是为了让事情简单(并且因为我无法在公交车上访问这篇文章......)

    public class Site {
        Integer id;
        String name;
        String rating;
        // .. Constructor and toString removed for brevity
    }

包装版本

稍后我将介绍一些主力类,但它们有点难看。这只是为了展示最终界面在您稍微包装一下后会是什么样子:

class SiteRepository { 
   private final MultiMap<Site> sites = new MultiMap<>();
   public final AbstractMap<String, Site> byName = sites.addIndex((site)->site.name);
   public final AbstractMap<Integer,Site> byId = sites.addIndex((site)->site.id);
   public final AbstractMap<String,List<Site>> byRating = sites.addMultiIndex((Site site)->site.rating);
   public void add(Site s) { sites.add(s); }
}

SiteRepository repo = new SiteRepository();
repo.add(...);
Site site = repo.byId.get(1234);
repo.byId.forEach((Integer id, Site s) -> System.err.printf("   %s => %s\n", id, s));

MultiMap 核心

可能应该被称为MultiIndex,因为MultiMap意味着其他东西......

    public static class MultiMap<V> {

        public static class MultiMapIndex<K,V> extends AbstractMap<K,V> {
            @Override
            public Set<Entry<K, V>> entrySet() {
                return map.entrySet();
            }
            HashMap<K,V> map = new HashMap<>();
       }


        public <K> MultiMapIndex<K,V> addIndex(Function<V, K> f) {
            MultiMapIndex<K,V> result = new MultiMapIndex<>();
            Consumer<V> e = (V v) -> result.map.put(f.apply(v), v);
            mappers.add(e);
            values.forEach(e);
            return result;
        }

        public <K> MultiMapIndex<K,List<V>> addMultiIndex(Function<V, K> f) {
            MultiMapIndex<K,List<V>> result = new MultiMapIndex<>();
            Consumer<V> e = (V v) -> {
                K key = f.apply(v);
                List<V> list = result.map.get(key);
                if (list == null) {
                    list = new ArrayList<>();
                    result.map.put(key, list);
                }
                list.add(v);
            };
            mappers.add(e);
            values.forEach(e);
            return result;
        }

        public void add(V v) {
            values.add(v);
            mappers.forEach( e -> e.accept(v));
        }

        private List<Consumer<V>> mappers = new ArrayList<>();
        private List<V> values = new ArrayList<>();    
    }

更多低级示例

    public static void main(String[] args) {
        // Create a multi-map
        MultiMap<Site> multiMap = new MultiMap<>();

        // Add an index by Site.id
        MultiMapIndex<Integer, Site> byId = multiMap.addIndex((site)->site.id);

        // Add some entries to the map
        multiMap.add(new Site(1234,"A Site","A"));
        multiMap.add(new Site(4321,"Another Site","B"));
        multiMap.add(new Site(7777,"My Site","A"));

        // We can add a new index after the entries have been
        // added - this time by name.
        MultiMapIndex<String, Site> byName = multiMap.addIndex((site)->site.name);

        // Get a value by Id.
        System.err.printf("Get by id=7777 = %s\n", byId.get(7777));
        // Get a value by Name
        System.err.printf("Get by name='A Site' = %s\n", byName.get("A Site"));  

        // We can do usual mappy things with the indexes,
        // such as list the keys, or iterate over all entries
        System.err.printf("byId.keys() = %s\n", byId.keySet());
        byId.forEach((Integer id, Site s) -> System.err.printf("   %s => %s\n", id, s));

        // In some cases the map is not unique, so I provide a 
        // way to get all entries with the same value as a list.
        // in this case by their rating value.
        MultiMapIndex<String, List<Site>> byRating = multiMap.addMultiIndex((Site site)->site.rating);
        System.err.printf("byRating('A') = %s\n", byRating.get("A"));
        System.err.printf("byRating('B') = %s\n", byRating.get("B"));

        // Adding stuff after creating the indices is fine.
        multiMap.add(new Site(3333,"Last Site","B"));
        System.err.printf("byRating('A') = %s\n", byRating.get("A"));
        System.err.printf("byRating('B') = %s\n", byRating.get("B"));
    }
}

关于java - 在Java中搜索具有不同键的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39325470/

相关文章:

java - 使用 Eclipse 添加继承方法签名的快速方法

Java 风格 XML 每行一个节点且无空格

java - 尝试使用正确的行标题创建 JTable

java - 动态创建实时视频流

ios - React-Native 谷歌地图搜索结果

java - 如何每秒改变圆圈的颜色

typescript - 如何在 typescript 的 webpack 中使用 seznam mapy?

java - 在移动应用程序中高效的本地存储和 map 访问?

android - 谷歌地图 Android API keystore

r - 如何将夏威夷和阿拉斯加添加到 R 中的空间多边形中?