排序HashMap的ArrayList的不同方法<string,string =“”> </string,>

时间:2015-01-09 16:37:58

标签: java android sorting arraylist

有很多与此相关的问题建议使用Comparator来比较和排序数据,我已经尝试过并努力使其发挥作用所以请不要将其报告为重复。< / p>

我有HashMap<String, String>

的arraylist
ArrayList<HashMap<String, String>>

并以此形式列出此列表中的数据

titlelinknumber是关键。

{ {title="",link="",number=}, {title="",link="",number=}, {title="",link="",number=} }

实施例,

{ {title,link,number = 8}, {title,link,number = 1}, {title,link,number = 3} }

应更改为,

{ {title,link,number = 1}, {title,link,number = 3}, {title,link,number = 8} }

我希望根据数字对其进行排序,我试过这个,

我创建了一个新类(如许多帖子所建议的,用于创建新类来比较数据),它实现了Comparator。

public class SortData implements Comparator<ArrayList<HashMap<String, String>>> 

自动实现的方法是,

@Override
    public int compare(ArrayList<HashMap<String, String>> lhs,
            ArrayList<HashMap<String, String>> rhs) {


        return 0;
    }

现在这个方法建议使用两个Hashmap的arraylist进行比较,但是因为我只有一个需要排序的arraylist所以我应该为第二个arraylist使用什么?

我的Arraylist名称是SecondArray,我想将它的每个值与下一个值进行比较,

 @Override
        public int compare(ArrayList<HashMap<String, String>> lhs,
                ArrayList<HashMap<String, String>> rhs) {

                lhs = SecondArray;
                rhs = // How to compare to the next value of the same Array ? 
            return 0;
        }

我应该如何将相同的arraylist与下一个值进行比较?

更新: 每个Array列表元素有三个键/值对,其中一个是数字,我想根据该数字对arraylist进行排序,这意味着,具有最小数字的键/值对应该是数组中的第一个列表。

5 个答案:

答案 0 :(得分:3)

将工具更改为Comparator<Hashmap<String,String>>并使用:

public int compare(HashMap<String, String>> lhs,
        HashMap<String, String>> rhs) {
    return Integer.compare(Integer.parseInt(lhs.get("number")),
        Integer.parseInt(rhs.get("number")));
}

我假设您的意思是(哈希)地图列表。

答案 1 :(得分:3)

强烈建议为3个变量创建一个数据保持类,并让该类实现Comarable(你可以像你一样创建一个实现Comparator的独立类显示,但我觉得更复杂)

实施可比较后,您可以使用Collections.sort对列表进行排序。

这里我举了一个简短的例子:

import java.util.*;
import java.lang.*;
import java.io.*;

class Data implements Comparable<Data>
{
    public static void main (String[] args) throws java.lang.Exception
    {
        List<Data> data = new ArrayList<Data>();
        data.add(new Data("Title1", "Link1", 8));
        data.add(new Data("Title2", "Link2", 1));
        data.add(new Data("Title3", "Link3", 3));

        for(Data d : data)
        {
            System.out.print(d.getNumber() + " ");
        }

        System.out.println();

        Collections.sort(data);

        for(Data d : data)
        {
            System.out.print(d.getNumber() + " ");
        }
    }

    private String title;
    private String link;
    private int number;

    public Data(){}
    public Data(String title, String link, int number)
    {
        setTitle(title);
        setLink(link);
        setNumber(number);
    }
    public void setTitle(String title)
    {
        this.title = title;
    }

    public void setLink(String link)
    {
        this.link = link;
    }

    public void setNumber(int number)
    {
        this.number = number;
    }

    public String getTitle()
    {
        return title;
    }

    public String getLink()
    {
        return link;
    }

    public int getNumber()
    {
        return number;
    }

    @Override
    public int compareTo(Data data)
    {
        return this.getNumber() - data.getNumber();
    }
}

输出:

8 1 3 
1 3 8 

您可以在Ideone

尝试此操作

答案 2 :(得分:2)

似乎你误解了比较器的概念。这个类应该提供一种方法来决定是否应该交换集合中的两个元素,因此它集中在集合的 content 上。

public class SortData implements Comparator<HashMap<String, String>>
//                                          ^^^^^^^^^^^^^^^^^^^^^^^

不是

public class SortData implements Comparator<ArrayList<HashMap<String, String>>>
// this would sort collection of -----------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
// like List<ArrayList<HashMap<String, String>>>

另外假设{title,link,number}是地图中的关键字,您的compare代码可能看起来像

public int compare(HashMap<String, String> o1, HashMap<String, String> o2) {
    int nr1= Integer.parseInt(o1.get("number"));
    int nr2= Integer.parseInt(o2.get("number"));
    return Integer.compare(nr1, nr2);
}

但是,如果您确定地图仅包含titlelinknumber的值,那么我会为此结构创建单独的类,例如

class Data{//you should also pick better name :)
    private String title;
    private String link;//you can also use URL here instead of String,
    private int number;
    //add getters and setters for each field like
    public int getNumber(){
        return number;
    }
}

这样你的比较器会更简单

public class SortData implements Comparator<Data>{

    @Override
    public int compare(Data o1, Data o2) {
        return Integer.compare(o1.getNumber(), o2.getNumber());
    }
}

或者实际上从Java 8开始,你甚至不需要明确地创建单独的比较器类。您可以使用Lambdas

隐式执行此操作
Comparator<Data> numberComparator =  (o1,o2)->Integer.compare(o1.getNumber(), o2.getNumber());

如果您想缩短代码,也可以使用方法参考

COmparator<Data> numberComparator = Comparator.comparingInt(Data::getNumber);

所以现在你的名单

List<Data> list = ...

可以像

一样排序
list.sort(numberComparator);

list.sort(Comparator.comparingInt(Data::getNumber));

答案 3 :(得分:1)

排序List Map的{​​{1}} s你想要对关键字“数字”进行排序时,我相信你应该使用它来代替:

    Collections.sort(myList, new Comparator<Map<String, String>>() {
        @Override
        public int compare(final Map<String, String> o1, final Map<String, String> o2) {
            // Do your sorting...
            return Integer.valueOf(o1.get("number"))
                          .compareTo(Integer.valueOf(o2.get("number")));
        }
    });

或者,如果您使用Java 8,则可以对List Map进行排序:

final List<Map<String, String>> sorted = 
    myList.stream()
          .sorted((m1, m2) -> Integer.valueOf(m1.get("number"))
                                     .compareTo(Integer.valueOf(m2.get("number"))))
          .collect(Collectors.toList());

答案 4 :(得分:1)

如何不使用Comparator类并简单地实现冒泡排序?

这样的事,

for (int c = 0; c < (yourArrayList.size() - 1); c++) {
            for (int d = 0; d < (yourArrayList.size() - c - 1); d++) {

                if (Integer.parseInt(yourArrayList.get(d).get("number")) > Integer
                        .parseInt(yourArrayList.get(d + 1).get("number"))) {

                    temporary = yourArrayList.get(d);
                    yourArrayList.set(d, yourArrayList.get(d + 1));
                    yourArrayList.set(d + 1, temporary);

                }
            }
        }

看看这个例子,

import java.util.ArrayList;
import java.util.HashMap;

public class Main {

    public static void main(String[] args) {

        ArrayList<HashMap<String, String>> yourArrayList = 
                new ArrayList<HashMap<String, String>>();

        HashMap<String, String> myHashMap = new HashMap<String, String>();

        myHashMap.put("title", "first Title");
        myHashMap.put("date", "This is 1st date");
        myHashMap.put("number", "5");
        yourArrayList.add(0, myHashMap);

        myHashMap = new HashMap<String, String>();

        myHashMap.put("title", "Second Title");
        myHashMap.put("date", "This is 2nd date");
        myHashMap.put("number", "2");
        yourArrayList.add(1, myHashMap);

        myHashMap = new HashMap<String, String>();

        myHashMap.put("title", "Third Title");
        myHashMap.put("date", "This is 3rd date");
        myHashMap.put("number", "7");
        yourArrayList.add(2, myHashMap);

        myHashMap = new HashMap<String, String>();

        myHashMap.put("title", "Fourth Title");
        myHashMap.put("date", "This is 4th date");
        myHashMap.put("number", "0");
        yourArrayList.add(3, myHashMap);

        System.out.println("=================");
        System.out.println("BEFORE SORTING");
        System.out.println("=================");

        for (int i = 0; i < yourArrayList.size(); i++) {
            System.out.println(yourArrayList.get(i));
        }

        HashMap<String, String> temporary;

        for (int c = 0; c < (yourArrayList.size() - 1); c++) {
            for (int d = 0; d < (yourArrayList.size() - c - 1); d++) {

                if (Integer.parseInt(yourArrayList.get(d).get("number")) > Integer
                        .parseInt(yourArrayList.get(d + 1).get("number"))) {

                    temporary = yourArrayList.get(d);
                    yourArrayList.set(d, yourArrayList.get(d + 1));
                    yourArrayList.set(d + 1, temporary);

                }
            }
        }

        System.out.println("=================");
        System.out.println("AFTER SORTING");
        System.out.println("=================");

        for (int i = 0; i < yourArrayList.size(); i++) {
            System.out.println(yourArrayList.get(i));
        }

    }

}

<强>输出

=================
BEFORE SORTING
=================
{date=This is 1st date, number=5, title=first Title}
{date=This is 2nd date, number=2, title=Second Title}
{date=This is 3rd date, number=7, title=Third Title}
{date=This is 4th date, number=0, title=Fourth Title}
=================
AFTER SORTING
=================
{date=This is 4th date, number=0, title=Fourth Title}
{date=This is 2nd date, number=2, title=Second Title}
{date=This is 1st date, number=5, title=first Title}
{date=This is 3rd date, number=7, title=Third Title}

您可以在此处测试 - &gt; http://goo.gl/0M3rBf