-1

オブジェクトのリストをJavaでマップに変換する方法、またはリストを処理する方法を見つけようとしています

請求書の例には、メモと金額の 2 つのフィールドがあります。

List<Invoice> invoices = Arrays.asList(
new Invoice( "note1", "amount1" ), 
new Invoice( "note2", "amount2" ) );

次のように、このリストをマップに取得できます。

Map<Long, String>
4

2 に答える 2

5

次のようなもの:

Map<Long, String> map = new HashMap<Long, String>();
for(Invoice invoice : invoces) {
    map.put(invoice.getId(), invoce.getName());
}

Longキーと値として具体的に何を保存したいかについて言及していないのでString、クラスInvoiceには長いIDと文字列名があると思いました。map.put(...)実際のニーズに合わせてラインを変更でき ます。

于 2012-08-29T17:27:19.567 に答える
0
public static Map<Long, String> invoicesToMap(List<Invoice> invoices) {
  Map<Long, String> map = new HashMap<Long, String>();
  for (Invoice invoice : invoices) {
    map.put(Long.valueOf(invoice.getAmount()), invoice.getNote());
  }
  return map;
}
于 2012-08-29T17:28:04.713 に答える