I have two list of objects like so :
class KeyValue {
KeyValue({required this.key, required this.value});
final String key;
final String value;
}
class CustomClass {
CustomClass({
required this.key,
required this.name,
this.value,
});
final String key;
final String name;
final String? value;
}
var listCustomClass = [
CustomClass(key: "1234", name: "name1"),
CustomClass(key: "1234", name: "name2"),
CustomClass(key: "12345", name: "name3"),
CustomClass(key: "12345678", name: "name4"),
];
final listKeyValue = [
KeyValue(key: "1234", value: "someValue1"),
KeyValue(key: "12345", value: "someValue2"),
KeyValue(key: "12345678", value: "someValue3"),
KeyValue(key: "123456789", value: "someValue4"),
];
I'd like to map listCustomClass
& listKeyValue
by key
in order to create
create a new List<CustomClass>
with each CustomClass()
taking its value
parameter from its matching KeyValue()
object (the one with the same key
)
it would create newListCustomClass
like so :
newListCustomClass = [
CustomClass(key: "1234", name: "name1", value: "someValue1"),
CustomClass(key: "1234", name: "name2", value: "someValue1"),
CustomClass(key: "12345", name: "name3", value: "someValue2"),
CustomClass(key: "12345678", name: "name4", value: "someValue3"),
];
CodePudding user response:
If listCustomClass
or listKeyValue
are large, you would be better off converting one of them to a Map
first. Since listCustomClass
apparently can have elements with the same key
, that one should stay a List
.
var mapKeyValue = {
for (var keyValue in listKeyValue) keyValue.key: keyValue.value,
};
var newListCustomClass = [
for (var customClass in listCustomClass)
CustomClass(
key: customClass.key,
name: customClass.name,
value: mapKeyValue[customClass.key],
),
];
If listCustomClass
has m elements and listKeyValues
has n elements, then the above code would be O(m n). If you store listKeyValues
as a Map
in the first place, then the code to convert from List
to Map
could be removed, and it would be just O(m).
CodePudding user response:
You can do it like
String getValue(String key) =>
listKeyValue.firstWhere((element) => element.key == key).value;
for (int i = 0; i < listCustomClass.length; i ) {
listCustomClass[i] =
listCustomClass[i].copyWith(value: getValue(listCustomClass[i].key));
}
And the class
class CustomClass {
CustomClass({
required this.key,
required this.name,
this.value,
});
final String key;
final String name;
final String? value;
@override
String toString() => 'CustomClass(key: $key, name: $name, value: $value)';
CustomClass copyWith({
String? key,
String? name,
String? value,
}) {
return CustomClass(
key: key ?? this.key,
name: name ?? this.name,
value: value ?? this.value,
);
}
}