2013-02-25 32 views
0

示例:一个查询引发下一个结果集:我怎样才能把一个大的数组列表分解成hashmap中的几个列表?

名称|年龄|总计

  • 约翰·史密斯,45,1000
  • 约翰·史密斯,56,800个
  • 约翰史密琴斯,34,500
  • 约翰·史密斯,56,500
  • 约翰·史密斯,56,1100

我想将这个数组列表分隔成三个,并将它们存储在一个hashmap中,其中key是客户端名称。

我想这样

Arraylist<Row> rows = dao.getClientActivity(); 
Map map = new HashMap<Clients Name, Clients Row>(); 
Arraylist<Row> = null; 


for (Row row : rows){ 

    if (map.get(row.clientName) == null) list = new ArrayList<Row>(); 

    list.add(row); 

    if(map.get(row.clientName) == null) map.put(row.clientName, list); 

} 

名单始终由名称进行排序。

将上面的代码片段作为伪代码,我没有家中的编码程序,我只是把它从头顶上取下来,我想我在这个星期五测试了类似的东西,但它只在行上打印;

我不知道是否有更好的方法来做到这一点,但这是我首先想到的。

回答

3

你映射声明应该如下(假设Row.clientNameString):

Map<String, List<Row>> map = new HashMap<String, List<Row>>(); 

而且for循环应该像下面这样:

for (Row row : rows){ 
    /*Get the list of rows for current client name.*/ 
    List<Row> currRows = map.get(row.clientName); 
    if (currRows == null) {/*If not list exists for*/ 
     currRows = new ArrayList<Row>(); /*create a new one*/ 
     map.put(row.clientName, currRows); /*and put it in the map*/ 
    } 
    currRows.add(row);/*add the current row to the list*/ 
} 
1

我假设不存在你可以改变输入格式。

我会建议你创建一个模型来表示一个客户端:

public class Client { 

    private final String name; 
    private final byte age; //Nobody should be older than 256 
    private final int total; 

    /* Construct model */ 

    /* Getters/Functions */ 

} 

我也建议你创建内部Client一个工厂方法来创建从你的字符串输入的类。

public static Client parseClient(String clientRep){ 

    String[] clientData = clientRep.split(','); 

    Client newClient = new Client(); //TODO: Name conventionally. 

    newClient.name = clientData[0]; 
    newClient.age = Byte.valueOf(clientData[1]); 
    newClient.total = Integer.valueOf(clientData[2]); 

    return newClient; 

} 

现在,您可以将这些添加到地图(Map<String, Client>)。

String clientFromWherever = getWhateverDataFromWherever(); 

Map<String, Client> clientel = new HashMap<>(); 

Client addingToMap = Client.parseClient(clientFromWherever); 

clientel.put(addingToMap.getName() /* or however the name should be got */, addingToMap); 

这应该做得很好。

=====

但是 - 如果你不应该要使用的客户端对象,我建议建立一个Map<String, int[]>和存储阵列中的年龄和充电。如果您的收费不超过Short.MAXVALUE请使用short[]。存储大量的阵列列表(或任何复杂的集合)只是为了存储少量的数据是不必要的。

ArrayList<Row> rows = dao.getClientActivity(); 
Map<String, int[]> clientelData = new HashMap<>(); 

for(Row clientRow : rows) { 

    if (!map.containsKey(clientRow.clientName) { 

     int[] clientNumericalData = new int[2]; 

     map.put(clientRow.clientName, clientNumericalData); 

    } 

} 
相关问题