jhenya-D:
オブジェクトフィールドがマップ値で始まる場合、条件付きマップからのデータでリストからオブジェクトを一致させ、別のマップに保存する方法を探しているソリューション
私はいくつかのデータをマッピングしています
Map<String, String> dataMap = new HashMap()
dataMap.put("d1", "DATA1")
dataMap.put("d2", "DATA2")
dataMap.put("d3", "DATA3")
そして、定義するDataElementオブジェクトのリストに
List<DataElement> elements = new ArrayList()
elements.add(new DataElement("TEXT1"))
elements.add(new DataElement("TEXT2"))
elements.add(new DataElement("DATA1_text1"))
elements.add(new DataElement("DATA2_text2"))
class DataElement {
public field;
public DataElement(String text){
this.field = text
}
public getField(){
return this.field
}
}
結果は次のようになります。そして、i'amは、オブジェクトフィールドがマップ値で始まる場合、キーは最初のマップと値からの値が条件でリストからオブジェクト(フィールド)されている新しいマップを取得しようとしています:
[d1=DATA1_text1, d2=DATA2_text2]
私のコード:
Map<String, String> collect2 = dataMap.entrySet().stream()
.filter({ map -> elements.stream()
.anyMatch({ el -> el.getField().startsWith(map.getValue()) })})
.collect(Collectors.toMap(KEY, VALUE))
彼らは次のとおりでした:
うまくいけば、私は右の質問を得ました:
Map<String, String> collect2 =
dataMap.entrySet()
.stream()
.map(e -> elements.stream()
// this will search for the first element of the List matching
// the value of the current Entry, if exists
.filter(el -> el.getField().startsWith(e.getValue()))
.findFirst()
// this will create a new Entry having the original key and the
// value obtained from the List
.map(el -> new SimpleEntry<>(e.getKey(),el.getField()))
// if findFirst found nothing, map to a null element
.orElse(null))
.filter(Objects::nonNull) // filter out all the nulls
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
あなたは、入力のエントリを処理しているMap
、との要素と一致する値があるエントリのみを保つList
(経由をfilter()
あなたには、いくつかの構文エラーを持っているもののを、)、しかし、あなたがする必要がmap
希望する新しい値が含まれている新しいエントリに入力項目。
この上記のコードは生成します Map
{d1=DATA1_text1, d2=DATA2_text2}
与えられた入力用。