【问题标题】:Guava Lists.transform - what if one input is bad?Guava Lists.transform - 如果一个输入不好怎么办?
【发布时间】:2013-01-14 12:05:51
【问题描述】:

我正在使用Lists.transform 方法。在此我有一个字符串输入和一个 CustomObject 输出。字符串输入应包含一个冒号。然后我在这个冒号上拆分,然后从字符串的两个部分创建自定义对象。

所以输入是

a:b
c:d
e:f

输出是三个CustomObject,包含a, bc, de, f

我的代码是这样的

return new ArrayList(Lists.transform(groups, new Function<String, CustomObject>() {
        @Override
        public CustomObject apply(String input) {
            String[] split = input.split(":");
            String one = split[0];
            String two = split[1];
            return new CustomObject(one, two);
        }
    }));

我的问题是我收到的列表来自用户。如果我输入错误,我想跳过列表中的那个项目

所以如果输入列表包含

a:b
d
e,f
g:h

那么我想要两个包含a:bg:h 的CustomObject

这在番石榴中可行吗?

如果我以冗长的方式执行此操作,我只会在 for 循环中继续并记录错误。

例如作为伪代码

for loop {
   if no colon present
      continue;
   create CustomObject
}

谢谢

【问题讨论】:

  • 我认为你可以使用旧的 for 循环。

标签: java collections exception-handling guava


【解决方案1】:

如果你真的不想走“经典”的路,你可以在转换之前使用Iterables.removeIf

但“旧循环”方式可能更适合您。 Guava 开发人员对滥用这些功能习语感到不满,因为他们explain here

过度使用 Guava 的函数式编程习惯会导致冗长、混乱、不可读和低效的代码。到目前为止,这些是 Guava 中最容易(也是最常见)被滥用的部分,当你为了让你的代码“单行”而竭尽全力时,Guava 团队会哭泣。

【讨论】:

  • +1。实际上,更实用的风格是使用 Iterables.filter 来清理输入,然后转换剩下的内容,但我同意不要滥用 guava。
【解决方案2】:

我的方法会更实用,我会使用FluentIterable

return FluentIterable.from(groups).transform(new Function<String, CustomObject>() {
        @Override
        public CustomObject apply(String input) {
            String[] split = Iterables.toArray(
               Splitter.on(':').trimResults().omitEmptyStrings().split(input),
               String.class);
            if(split.length!=2) return null; // bad input data
            String one = split[0];
            String two = split[1];
            return new CustomObject(one, two);
        }
    }).filter(notNull()).toImmutableList();
         //   ^^  -- Predicates.*     

我会将 Function 和 Splitter 都转换为常量。

【讨论】:

  • 或直接Predicates.notNull()
  • @FrankPavageau 很好,我错过了 :-) 现在改变了我的答案
【解决方案3】:

您可以更改您的函数以返回一个 Optional,并使用 Optional.presentInstances():

    return Optional.presentInstances(Iterables.transform(groups, new Function<String, Optional<CustomObject>>() {
        @Override
        public Optional<CustomObject> apply(String input) {
            if (*/ bad input data */) {
                return Optional.absent();
            }
            // ...
            return Optional.of(new CustomObject("", ""));
        }
    }));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-09
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多