Google Collections Distinct Predicate

寵の児 提交于 2019-12-23 19:28:07

问题


How would one implement a distinct predicate for use with the Google Collections Collections2.filter method?


回答1:


If I understand you correctly, I'm not sure that Predicate is the right solution here:

Creating a predicate like that would require maintaining some sort of state (ie: maintaining a Set of things it has seen already). This is explicitly advised against in the javadoc.

The usual way to get the distinct items in a collection would be to just add them all to a set. ie:

Set<T> uniqueItems = Sets.newHashSet(collectionWithPotentialDuplicates);

If the equals() and hashCode() methods on <T> don't define uniqueness the way you want, then you should write a utility method that operates on a Collection<T> and a Function<T, Object> which returns the items of type T which are unique after being converted using the Function




回答2:


My solution:

// Create unique list
final Set<String> unique = new HashSet<String>(FluentIterable
                                                .from(sourceList)
                                                .transform(new Function<T, String>() {
                                                    @Override
                                                    public String apply(T input) {
                                                        // Here we create unique entry
                                                        return input.toString(); 
                                                    }
                                                }).toSet());
// Filter and remove duplicates
return FluentIterable
        .from(prePscRowList)
        .filter(new Predicate<T>() {
            @Override
            public boolean apply(T input) {
                boolean exist = false;
                if(unique.contains(input.toString())){
                    unique.remove(input.toString());
                    exist = true;
                }
                return exist;
            }
        }).toList();


来源:https://stackoverflow.com/questions/4036326/google-collections-distinct-predicate

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!