Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 列表的高效过滤_Java_List_Dictionary_Guava_List Comprehension - Fatal编程技术网

Java 列表的高效过滤

Java 列表的高效过滤,java,list,dictionary,guava,list-comprehension,Java,List,Dictionary,Guava,List Comprehension,我有一张单子。让我们称之为newList。现在,类A有两个属性id和权重。现在,newList包含各种类型的条目A。我想要的是一个包含id->weight的映射,这样就映射了最重的一个,我指的是具有特定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 ob

我有一张单子。让我们称之为newList。现在,类A有两个属性id和权重。现在,newList包含各种类型的条目A。我想要的是一个包含id->weight的映射,这样就映射了最重的一个,我指的是具有特定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

我现在做的是一个接一个地迭代列表,检查给定的keyid,即已经存在的valueweight,如果我的当前值更大,则覆盖它。虽然这很好。我想我可以尝试用番石榴做一些更优雅的列表。有什么帮助吗?

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


请参阅以获取一些示例。

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

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));
        }
将其与vanilla 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提出一个解决方案,那将很有帮助。

此链接指向2004年的一篇文章!没有泛型和公共库…您能使用Java8吗?吃番石榴可能会有点难。