【问题标题】:Elegant way of doing ruby inject in Java 8在 Java 8 中进行 ruby​​ 注入的优雅方式
【发布时间】:2015-12-08 18:15:54
【问题描述】:
String result = "";
for(String str : strings) {
    result = apply(result, str);
}
return result;

我想通过循环中的下一个元素传递一个操作的结果。在 Java 8 中是否有任何优雅的方法可以做到这一点?

例如,在Ruby中,我们可以使用inject。

strings.inject("") { |s1, s2| apply(s1,s2) }

【问题讨论】:

    标签: java loops java-8


    【解决方案1】:

    你可以使用reduce

    String result = strings.stream().reduce("", this::apply);
    

    【讨论】:

    【解决方案2】:

    如果您不介意添加第三方库,可以使用Eclipse Collections,它在其对象和原始容器上具有injectInto 方法。 Eclipse Collections 的灵感来自 Smalltalk Collections API,后者也启发了 Ruby。以下是使用 injectInto 的对象(可变和不可变)和原始(可变和不可变)容器的一些示例。

    @Test
    public void inject()
    {
        MutableList<String> strings1 = Lists.mutable.with("1", "2", "3");
        Assert.assertEquals("123", strings1.injectInto("", this::apply));
    
        ImmutableList<String> strings2 = Lists.immutable.with("1", "2", "3");
        Assert.assertEquals("123", strings2.injectInto("", this::apply));
    
        IntList ints = IntLists.mutable.with(1, 2, 3);
        Assert.assertEquals("123", ints.injectInto("", this::applyInt));
    
        LazyIterable<Integer> boxedInterval = Interval.oneTo(3);
        Assert.assertEquals("123", boxedInterval.injectInto("", this::applyInt));
    
        IntList primitiveInterval = IntInterval.oneTo(3);
        Assert.assertEquals("123", primitiveInterval.injectInto("", this::applyInt));
    }
    
    public String apply(String result, String each)
    {
        return result + each;
    }
    
    public String applyInt(String result, int each)
    {
        return result + each;
    }
    

    注意:我是 Eclipse Collections 的提交者

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-01
      • 1970-01-01
      • 2020-01-28
      • 1970-01-01
      • 2021-11-10
      • 2010-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多