オプションの内容や流れをキャスト

michaeak:

私の代わりに自分自身のメソッドやクラスを書くの私はちょうどチェックできるし、別のクラスにオプションの内容を鋳造または空のオブジェクトを持っていたいです。

アプリケーションでこのサブ問題のために私はインスタンスのカスタムユーザオブジェクトを持つようにしたいTreeNodeにキャストCustomUserObjectすることを提供する、TreeNodeのインスタンスですDefaultMutableTreeNode

private Optional<CustomUserObject> getCustomUserObject(TreeNode node) {
    Optional<DefaultMutableTreeNode> optDefaultMutableTreeNode = OptionalUtil.cast(Optional.ofNullable(node), DefaultMutableTreeNode.class);
    Optional<Object> optUserObject = optDefaultMutableTreeNode.map(DefaultMutableTreeNode::getUserObject); //
    return OptionalUtil.cast(optUserObject, CustomUserObject.class);
}


/**
 * Maps the given optional, if the containing element is an instance of the given class.
 * Returns empty if the containing object is not an instance of the given class.
 * 
 * @param orgOptional
 *        given optional
 * @param clazz
 *        given class.
 * @return the resulting {@link Optional}.
 */
public static <T, X> Optional<T> cast(Optional<X> orgOptional, Class<T> clazz) {
    return orgOptional //
        .filter(clazz::isInstance) // check instance
        .map(clazz::cast); // cast
}

/**
 * Maps the given stream, if the containing element is an instance of the given class.
 * Returns empty if the containing object is not an instance of the given class.
 * 
 * @param orgStream
 *        given optional
 * @param clazz
 *        given class.
 * @return the resulting {@link Optional}.
 */
public static <T, X> Stream<T> cast(Stream<X> orgStream, Class<T> clazz) {
    return orgStream //
        .filter(clazz::isInstance) // check instance
        .map(clazz::cast); // cast
}

私はかなり頻繁にこのようにキャストoptionalsまたはストリームに必要覚えています。それは流暢ではありません。実際に私は、javaオプションまたはストリームは、上記の手順を行いキャスト法を持ってほしいです。私は自分の流暢CustomOptionalを書きたくはありません。私は何を欠場しましたか?簡単な方法でこれを行う方法はありますか?

ディディエ・L:

あなたは簡単に依存することによってこれをより堪能することができますmap()/ flatMap()およびcastメソッドの代わりにリターン機能します。

以下のためにOptional、これは非常に簡単以来でmap()返すことにより、フィルタとして機能することができますnullだから定義します。

public static <U> Function<Object, U> filterAndCast(Class<? extends U> clazz) {
    return t -> clazz.isInstance(t) ? clazz.cast(t) : null;
}

それを使用します:

Optional<Number> number = Optional.of(42L);
System.out.println(number.map(filterAndCast(Integer.class)));
System.out.println(number.map(filterAndCast(Long.class)));

出力:

Optional.empty
Optional[42]

ストリームの場合、あなたがに頼ることにより、多かれ少なかれ同じトリックを適用することができますflatMap()戻って空という機能をStream

public static <U> Function<Object, Stream<U>> streamFilterAndCast(Class<? extends U> clazz) {
    return t -> clazz.isInstance(t) ? Stream.of(clazz.cast(t)) : Stream.empty();
    // or alternatively
    return t -> Stream.of(t).filter(clazz::isInstance).map(clazz::cast);
}

それを使用します:

Stream.of(42L, "Hello world", 1024, 3.14)
        .flatMap(streamFilterAndCast(Number.class))
        .forEach(System.out::println);

出力:

42
1024
3.14

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=212670&siteId=1