1:
私は、Listオブジェクトを持っていると私はそれがnullまたは空でない場合は、リスト上の最初の要素を取る必要があります。
私は、javaを使用してコードの下に書いて、今私は、Java 8に変換します。
List<DD> container
A<DD,DI> a;
if(container!=null || !container.isEmpty()){
for(DD dd:container)
{
a = dd.getPrescription();
break;
}
}
私はこのようにそれを変換します。
DD detail = container.stream().findFirst().get();
私はこれが正しいことを知っている必要がありますか?
また:
あなたの現在のコード、つまりにおける重要な問題が存在します
if(container!=null || !container.isEmpty())
これはまだ投げることができますNullPointerException
(ときcontainer == null
)、条件演算子に変更されない限り&&
。ポストその実装は、以下の私は、次のことをお勧めするものだろう。
それはあなたが条件が満たされていない場合は、いくつかのデフォルト値を処理する必要があるという意味で、ほとんど正しいです。
DD detail = container.stream().findFirst().orElse(null); // or some default value instead of 'null'
場合はcontainer
、それ自体がnull、使用することができ
DD detail = container != null ?
container.stream().findFirst().orElse(null) : null;
あなたは、このオブジェクトからの処方箋を必要とする場合には、使用しmap
て:
container.stream().findFirst().map(DD::getPrescription).orElse(null)
// ^^
// return type of prescription then
Javaの-9で、これはとはるかに簡単だったかもしれません。
A<DD, DI> basePrescription = Stream.ofNullable(container) // Java-9 API
.flatMap(List::stream)
.findFirst()
.map(DD::getPrescription)
.orElse(null);