2016-06-23 15 views
0

2つの異なるオブジェクトに基づいて新しいオブジェクトを作成する最適な方法は何ですか。Javaストリームは、2つの異なるオブジェクトに基づいて新しいオブジェクトを作成します。

私はjavaストリームを使いたいと思います。

私の2つのスタートは、私が結果オブジェクトの配列を取得したいと私は

List<EventA> eventAList; 
List<EventB> eventBList; 

のような2つのオブジェクトの配列を持っている

public class EventA{ 
    Long id; 
    String name; 
    ... 
    Long locationID; 
} 

public class EventB{ 
    Long id 
    String Name; 
    ... 
    Long locationID; 
} 

そして、私の結果クラス

public class Result{ 
    Long locationID; 
    String eventAName; 
    String eventBName; 

    public Result(...){...} 
} 

オブジェクト。すべてイベントAの名前をresultListにコピーする必要があります。同じ場所にイベントBが存在する場合は、この名前をeventBNameに保存したいと考えています。

私がこれまで行ってきたすべてが、私はコンストラクタにEventBから値を渡す方法がわからない

List<Result> resultList = eventAList.stream().map(e -> new Result(e.locationID, e.name, null)).collect(Collectors.toList()); 

ある

+0

をeventBlistためのマップを作成し、彼らは実質的に同一のプロパティを表示するので、あなただけの、 'EventA'と' EventB'に共通の祖先を持っていないことはできますか? 'List 'をストリームして... – Mena

+0

いいえ、私の例を単純化するだけです。実際には全く異なっています –

+0

「同じ場所にいる」とはどういう意味ですか?同じ 'locationID'または' 'eventAList'と' eventBList'の同じインデックスにありますか? –

答えて

2

あなたResultを作成するときは、にストリームを使用することができますeventBListの値を繰り返し、eventAListの値と同じlocationIDの値を保持してから、見つけた値をmap()とし、Nameの値またはにします210は、それが存在しない場合:

List<Result> resultList = eventAList.stream().map(a -> new Result(a.locationID, a.name, 
    eventBList.stream().filter(b -> b.locationID.equals(a.locationID)).findAny().map(b -> b.Name).orElse(null) 
)).collect(Collectors.toList()); 

より良いパフォーマンスのために、あなたは一時的Map使用することができます。

final Map<Long, String> eventBMap = eventBList.stream().collect(Collectors.toMap(b -> b.locationID, b -> b.Name)); 

List<Result> resultList = eventAList.stream().map(a -> new Result(a.locationID, a.name, 
    eventBMap.get(a.locationID) 
)).collect(Collectors.toList()); 
1

は私が結果のコンストラクタを調整する作業方法

を見つけましたクラスから

public Result(Long locationID, String eventAName, EventB eventB){ 
    this.locationID = locationID; 
    this.eventAName = eventAName; 
    this.eventBName = eventB.name; 
} 

私のJavaストリームの中に入れてください。

List<Result> resultList = eventAList.stream().map(ea -> new Result(ea.locationID, ea.name, eventBList.stream().filter(eb -> eb.locationID.equals(ea.locationID)).findFirst().orElse(new EventB()).get()).collect(Collectors.toList()); 
1

あなたは次のようなことができますし、後で機能強化します。 )より高速な検索を持つためにキーとしてlocationIdによって

Function<EventA, SimpleEntry<EventA, Optional<EventB>>> mapToSimpleEntry = eventA -> new SimpleEntry<>(eventA, 
    eventBList.stream() 
    .filter(e -> Objects.equals(e.getLocationID(), eventA.getLocationID())) 
    .findFirst()); 

Function<SimpleEntry<EventA, Optional<EventB>>, Result> mapToResult = simpleEntry -> { 
    EventA eventA = simpleEntry.getKey(); 
    Optional<EventB> eventB = simpleEntry.getValue(); 
    return new Result(eventA.getLocationID(), eventA.getName(), eventB.map(EventB::getName).orElse(null)); 
}; 

eventAList.stream() 
    .map(mapToSimpleEntry) 
    .map(mapToResult) 
    .collect(Collectors.toList()); 
関連する問題