Dart Object ListのKey-valueで重複を削除する方法
- 2023年3月31日
- 技術情報
DartでKey-ValueによるObjectのリストから重複を削除するには、toSet()が利用できます。最初にtoSetメソッドを呼び出し、その後、再びリストに変換するだけです。
以下に例を示します。
class _Product {
final name;
final type;
final price;
_Product({
required this.name,
required this.type,
required this.price,
});
String toJson() {
return "{ name: $name, type: $type, price: $price}";
}
}
toSetを呼び出してみます。
final products = [
_Product(name: "USB", type: "A", price: 10), // same
_Product(name: "USB", type: "A", price: 10), // same
_Product(name: "USB", type: "B", price: 12),
_Product(name: "USB", type: "C", price: 11),
_Product(name: "Mouse", type: "A", price: 10),
_Product(name: "Mouse", type: "B", price: 12), // same
_Product(name: "Mouse", type: "B", price: 12), // same
_Product(name: "Mouse", type: "C", price: 10),
_Product(name: "Laptop", type: "A", price: 100),
_Product(name: "Laptop", type: "B", price: 120), // same
_Product(name: "Laptop", type: "B", price: 120), // same
];
print(products.length); // 11
print(products.toSet().length); // 11
toSet()で呼び出しても、同じ長さになっています。その時、hashCodeを確認してみます。
products.forEach((element) {
print(element.hashCode);
// 257416280
// 1045932166
// 730517725
// 586146378
// 215518337
// 471982393
// 775971279
// 335683510
// 844714385
// 633234047
// 1021163746
});
それぞれのhashCodeは異なっているため、hashCodeと==演算子をオーバーライドする必要があります。
class _Product {
...
@override
bool operator ==(Object other) {
return other is _Product && other.hashCode == hashCode;
}
@override
int get hashCode => Object.hash(name, type, price);
}
このクラスはリストを持ちませんから、Object.hash関数を使用しますが、リスト変数を含む場合は、代わりにObject.hashAllを使用します。
もう一度、toSetを呼び出してみます。
print(products.length); // 11
print(products.toSet().length); // 8
products.toSet().forEach((element) => print(element.toJson()));
// { name: USB, type: A, price: 10}
// { name: USB, type: B, price: 12}
// { name: USB, type: C, price: 11}
// { name: Mouse, type: A, price: 10}
// { name: Mouse, type: B, price: 12}
// { name: Mouse, type: C, price: 10}
// { name: Laptop, type: A, price: 100}
// { name: Laptop, type: B, price: 120}
なお、重複するものはここでは表示しませんでした。
金曜担当 – Ami
asahi at 2023年03月31日 11:00:00