Java HashMap在循环迭代中失去价值

时间:2011-04-28 17:24:00

标签: java android map hashmap

我正在尝试按字母顺序重新排序地图列表。我可以看到“name”字符串被填充了适当的值,但groupDataCopy永远不会更新。据我所知,使用new运算符并调用“put”会将值放在Map中。但我可以看到,在接下来的迭代中,ArrayList包含:

 {name = null}

我不知道为什么我在地图列表中丢失了值。这是代码:

private void sortByName() {
    List<Map<String, String>> groupDataCopy = new ArrayList<Map<String, String>>();
    List<List<Map<String, String>>> childDataCopy = new ArrayList<List<Map<String, String>>>();
    int groupPos = 0;
    int nextNamePos = 0;
    String name = null;

    while(groupPos<groupData.size()) {
        //main loop
        int groupDataComparison = 0;
        name = null;

        while(groupDataComparison<groupData.size()) {
            //comparison traversal for group
            if(!groupDataCopy.isEmpty()) {  //if groupDataCopy has data
                if(groupDataCopy.get(groupDataCopy.size()-1).get("name").compareTo(groupData.get(groupDataComparison).get("name")) > 0) {   //if the last index of groupDataCopy is alphabetically after (or equal to) last chosen name
                    if(name==null || groupData.get(groupDataComparison).get("name").compareTo(name) < 0) {
                        name = groupData.get(groupDataComparison).get("name");
                        nextNamePos = groupDataComparison;
                    }
                }
            } else {
                if(name==null || groupData.get(groupDataComparison).get("name").compareTo(name) < 0) {
                    name = groupData.get(groupDataComparison).get("name");
                    nextNamePos = groupDataComparison;
                }
            }
            groupDataComparison++;
        }
        groupDataCopy.add(new HashMap<String, String>());
        groupDataCopy.get(groupPos).put("name", name);
        childDataCopy.add(new ArrayList<Map<String, String>>());
        for(Map<String, String> data : childData.get(nextNamePos)) {
            childDataCopy.get(groupPos).add(data);
        }
        groupPos++;
    } 

    groupData = groupDataCopy;
    childData = childDataCopy;
}

2 个答案:

答案 0 :(得分:1)

Comparator<Map<String, String> comparator = new Comparator<Map<String, String>()
{
    public int compare(Map<String, String> o1, Map<String, String> o2) 
    {
        return o1.get("name").compartTo(o2.get("name");
    }
}

Collections.sort(groupData, comparator);

答案 1 :(得分:0)

尝试创建一个可让您使用Collections.sort的比较器:

类似的东西:

Comparator<Map<String, String> comp = new Comparator<Map<String, String>()
{
    public int compare(Map<String, String> o1, Map<String, String> o2) 
    {
        //write code to compare values
    }
}

之后你可以简单地做:

Collections.sort(groupData, comp);