2016-07-26 68 views
1

我想知道检索列表中列表元素的最佳方法。Java:检索列表中的值的最佳方法

  List<Object> totalsList = new ArrayList<Object>();  
      Map<String, Object> grandTotalsMap = new HashMap<String, Object>();    
      List<Map<String, String>> items = new ArrayList<Map<String, String>>(); 

      Map<String, String> lineItemsMap1 = new HashMap<String, String>();  
      lineItemsMap1.put("amount", "$70.00"); 
      lineItemsMap1.put("period", "Monthly"); 

      Map<String, String> lineItemsMap2 = new HashMap<String, String>();  
      lineItemsMap2.put("amount", "$55.00"); 
      lineItemsMap2.put("period", "Bi-Monthly"); 

      items.add(lineItemsMap1); 
      items.add(lineItemsMap2); 

      grandTotalsMap.put("section" , "total per pay period amounts"); 
      grandTotalsMap.put("title", "You'r amount"); 
      grandTotalsMap.put("lineItems", items);  

** //我期待输出:我想创建一个新的地图,并把类似下面的键值:

{ 
    amount: $70.00, 
    period: Monthly, 
    }, 

    { 
    amount: $55.00, 
    period: Bi-Monthly, 

    } 

**

+0

你可以在'lambda'中使用'lambda' – emotionlessbananas

+0

'ArrayLists'有一个'arrayListObject.get(int index)'方法,可以用来获取列表中的各个元素。 –

回答

0

你的情况,使用items.get(int index)将返回一个HashMap,该HashMap对应于存储地图的数组中的位置。例如,items.get(0)会返回您添加的第一张地图(lineItemsMap1),而items.get(1)会返回您添加的第二张地图(lineItemsMap2)。

一旦您找到了正确的地图,您就可以致电HashMap.get(String columnName)来检索您存储的值。是访问存储在您的ArrayList中的信息

两种不同的方式如下:

HashMap<String, String> map = items.get(0); 
String amount = map.get("amount"); // This will return '$70.00' 
String period = map.get("period"); // This will return 'Monthly' 

OR

String amount = items.get(0).get("amount"); // Returning '$70.00' 
String period = items.get(0).get("period"); // Returning 'Monthly' 

如果您正在寻找创建这些值的新地图,您可以将它们存储在局部变量中(如上所述),然后在创建它时将这些变量添加到映射中:

HashMap<String, String> newMap = new HashMap<String, String>(); newMap.put("newAmount", amount);

或者,你可以通过创建地图时直接访问ArrayList中添加值:

newMap.put("newAmount", items.get(0).get("amount")); 

希望这有助于!

相关问题