【问题标题】:Efficient filtering of list高效过滤列表
【发布时间】:2015-07-02 14:20:24
【问题描述】:

我有一个List<A>。让我们称之为newList。现在类A 有两个属性idweight。现在newList 包含A 类型的各种条目。我想要的是一个包含 id->weight 的 Map ,以便映射特定 id 的最重(我指的是具有最高权重值的那个)实例。

Example say the List contains the following objects:
obj1: id=1 weight=5
obj2: id=1 weight=10
obj3: id=1 weight=12
obj4: id=2 weight=6
obj5: id=2 weight=7 

地图应该是

id:1->weight:12
id:2->weight:7

我目前正在做的是逐个迭代列表并检查给定的键(id)什么是已经存在的值(权重),如果我的当前值更大,则覆盖。虽然这很好。我在想可能有一些更优雅的列表理解我可以尝试使用番石榴。有什么帮助吗?

【问题讨论】:

  • 你可以使用 Java 8 吗?使用番石榴可能会更难一些。

标签: java list dictionary guava list-comprehension


【解决方案1】:

这是我能想到的使用 Guava 的最佳解决方案:

Map<Integer,Integer> finalMap=Maps.newHashMap();
Multimap<Integer,A> newMap=Multimaps.index(newList, new Function<A,Integer>(){
            public Integer apply(A input) {
                return input.getId();
            }
        });
for(Integer i:newMap.keySet()){
            List<Integer> z=FluentIterable.from(newMap.get(i))
                            .transform(new Function<A,Integer>(){
                                public Integer apply(A input) {
                                    return input.getWeight();
                                }
                            }).toList();
            finalMap.put(i, Collections.max(z));
        }

将其与普通 Java 6 进行比较

Map<Integer,Integer> finalMap=new HashMap<Integer,Integer>();
for(A a:newList){
    if(finalMap.get(a.getId())!=null){
    finalMap.put(a.getId(),finalMap.get(a.getId())>a.getWeight()?finalMap.get(a.getId()):a.getWeight());
    }
    finalMap.put(a.getId(), a.getWeight());
}

好像是这样的

过度使用 Guava 的函数式编程习惯会导致 冗长、混乱、不可读和低效的代码。这些是迄今为止 番石榴最容易(也是最常见)被滥用的部分,以及何时 你竭尽全力让你的代码“单行” 番石榴队哭泣

如果有人可以在 Java 8 中提出解决方案,那将会有所帮助。

【讨论】:

    【解决方案2】:

    您好,您使用 FilterCriteria 来完成此任务。

    有关示例,请参阅link

    【讨论】:

    • 此链接指向 2004 年的一篇文章(!),没有泛型和通用库...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 2010-09-23
    • 2018-05-01
    • 2021-07-01
    • 2019-07-27
    相关资源
    最近更新 更多