9

How can I decompose a large arrayist into several arrraylists in a hashmap?

 2 years ago
source link: https://www.codesd.com/item/how-can-i-decompose-a-large-arrayist-into-several-arrraylists-in-a-hashmap.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

How can I decompose a large arrayist into several arrraylists in a hashmap?

advertisements

Example: One query throws the next result set:

Name | Age | Grand Total

  • John Smith, 45, 1000
  • John Smith, 56, 800
  • John Smithers, 34, 500
  • John Smyth, 56, 500
  • John Smyth, 56, 1100

I want to separate this arraylist into three, and store them in a hashmap where the key is the client name.

I was thinking something like

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);

}

The list will always be sorted by name.

Take the upper snippet as pseudo code, I don't have coding programs at home, I just got that off the top of my head, I think I tested something like that this friday but it only printed on row;

I don't know if there's a better way to do this, but this is the first thing I come up with.


Your map declaration should be as follows (assuming Row.clientName is String):

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

And the for loop should look like as follows:

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*/
}


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK