【问题标题】:How can I use guava FluentIterable to simplify Maps transformations?如何使用 guava FluentIterable 来简化 Maps 转换?
【发布时间】:2014-04-30 21:22:19
【问题描述】:

我经常使用Map<U,V>,我转换和过滤得到另一个Map<U,V'>,但是转换非常冗长,我在问题Guava: how to combine filter and transform?中看到FluentIterable类,是否可以使用它来简化下列的 ?

public class GuavaTest {

    public static class A{
        int a;
        int b;
        int c;
        public A(int a, int b, int c){
            this.a=a; this.b=b; this.c=c;
        }
    }

    public static void main(String[] args) {

        //Example 2
        final Map<String, A> map =Maps.newHashMap();

        map.put("obj1",new A(1,1,1)); map.put("obj2",new A(1,2,1));
        map.put("obj3",new A(1,3,1)); map.put("obj4",new A(1,4,1));

        Function<A, Integer> function = new Function<A, Integer>() {
            @Nullable
            @Override
            public Integer apply(@Nullable A input) {
                return input.b;
            }
        };

        Predicate<Integer> isPair = new Predicate<Integer>() {
            @Override
            public boolean apply(@Nullable Integer input) {
                return input % 2 == 0;
            }
        };

        //Can I use FluentIterable here ??
        Map<String, Integer> stringIntegerMap = Maps.transformValues(map, function);
        Map<String, Integer> stringIntegerMap1 = Maps.filterValues(stringIntegerMap, isPair);
    }
}

【问题讨论】:

    标签: java guava generic-programming


    【解决方案1】:

    没有。

    FluentIterable 并没有真正对地图做任何事情,当然也不会缩短您的 FunctionPredicate 实现。唯一能缩短这些的是 Java 8 lambdas,真的。

    【讨论】:

    • 谢谢,所以这个没有表情糖?
    • Java 8 lambdas 使这变得更好,但您使用的静态 Maps 方法已经存在。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-02-22
    • 2013-12-03
    • 1970-01-01
    • 2013-07-31
    • 2020-03-01
    • 1970-01-01
    • 2013-10-10
    相关资源
    最近更新 更多