具有特定结构的现成对象包装器 class

Ready object wrapper class with specific structure

简短的问题。

出于某些目的,尤其是在 java-8 及其流中,使用这样的包装器 class 很方便:

class ObjectWrapper<T> {
   T obj;
   boolean set(T obj) {
      this.obj = obj;
      return true;
   }
}

使用它 stream().filter(...) 条件用自定义对象(不同于集合项目)填充搜索结果可能会很好。

java-8中是否有类似的class?


编辑 人们要求使用示例。好的。这是一个非常牵强的例子,但它表明了主要思想:找到奇数长度的第一个单词并保存(return)它的长度。

    List<String> collection = Arrays.asList("ab", "abc3d", "ab", "affdd");

    class ObjectWrapper<T> {
        T obj;
        boolean set(T obj) {
            this.obj = obj;
            return true;
        }
    }

    ObjectWrapper<Integer> oddWordLength = new ObjectWrapper<Integer>();

    collection.stream().filter(s -> s.length() % 2 != 0 && oddWordLength.set(s.length())).findFirst();

你的例子:

List<String> collection = Arrays.asList("ab", "abc3d", "ab", "affdd");

find first word with odd length and save (return) its length.

一个简单的解决方案:

return  collection.stream()
                  .filter(s -> s.length() % 2 != 0)
                  .mapToInt(String::length)
                  .findFirst()

请注意,这将 return 一个 OptionalInt,因此如果您的 List 为空,它将 return OptionalInt.empty().

不需要你的支架class。