ArrayList 转换为Map

弄了两三个小时,终于解决了。
实现功能
Object对象包括两变量,id和name
将ArrayList中的id转变为Map中的key值,将与id对应的name放入Map的ArrayList中
使用的方法:遍历Map,使用

for (Map.Entry<Integer, ArrayList<String>> entry : nodeMap.entrySet())

需要注意的地方
最后将list放入map之后清空,
不能使用 list.clear(),
要使用 userList = null;

package com.ws.map;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapTest {
    public static void main(String[] args) {
        Map> nodeMap = new HashMap>();

        List list = new ArrayList();
        User user1 = new User(1, "a");
        User user2 = new User(2, "a");
        User user3 = new User(3, "a");
        User user4 = new User(1, "aaa");
        User user5 = new User(2, "aaa");
        User user6 = new User(3, "aaa");
        User user7 = new User(4, "aaa");
        User user8 = new User(5, "bbb");
        User user9 = new User(6, "ccc");
        User user10 = new User(4, "ddd");
        list.add(user1);
        list.add(user2);
        list.add(user3);
        list.add(user4);
        list.add(user5);
        list.add(user6);
        list.add(user7);
        list.add(user8);
        list.add(user9);
        list.add(user10);

        for (User user : list) {
            nodeMap.put(user.getId(), new ArrayList());
        }

        Map> map = new HashMap>();
        for (Map.Entry> entry : nodeMap.entrySet()) {
            ArrayList userList = new ArrayList();
            for (User user : list) {
                if (entry.getKey() == user.getId()) {
                    userList.add(user.getName());
                }
            }
            map.put(entry.getKey(), userList);
            userList = null;
        }
        System.out.println();
    }
}

class User {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }
}

你可能感兴趣的:(Java语言常见问题)