ArrayList排序为String,int

时间:2013-04-09 17:32:45

标签: java arrays collections arraylist

我希望根据ArrayList<String,int>类型int进行排序。

所以,我的变量是var<String,int>

India    2
Pakistan 3
USA      1

输出变为:

USA      1
India    2
Pakistan 3

我很困惑它如何与int一起使用。 Collections.sort(var)无效。

6 个答案:

答案 0 :(得分:4)

您不能使用

类型的ArrayList
 <String, int>
  1. 由于ArrayList保存对象,因此无法在ArrayList中使用基元。因此,您可以做的最接近的是存储Integer对象。
  2. 如果要对其进行参数化,则ArrayList只能是一种类型。
  3. 如果要保存String和int,可以使用字段名称和等级创建一个CountryInfo类。然后创建

      ArrayList<CountryInfo> list =new ArrayList<CountryInfo>();
    

    然后你可以使用

      Collections.sort(list, <Comparator>)
    

答案 1 :(得分:0)

这不是ArrayList。在Stead中使用TreeMap。

 Map<String, Integer> countryInfo = new TreeMap<String,Integer>();

这样它会自动排序

答案 2 :(得分:0)

ArrayList是一种对象的集合。它不像地图可以采取两个输入。

因此,有三个选项:

<强> 1。使用包含Key和Map的TreeMap,并按键或

自动排序

<强> 2。使用未排序的地图并使用比较器排序 - 请参阅Sort a Map<Key, Value> by values (Java)

第3。使用带比较器的自定义类的arraylist。

-

1)使用TreeMap

树图是红黑树的一种实现方式。请参阅:http://docs.oracle.com/javase/1.5.0/docs/api/java/util/TreeMap.html

    TreeMap<Integer,String> countries = new TreeMap<Integer,String>();
    countries.put(2, "India");
    countries.put(1, "USA");
    countries.put(3, "Pakistan");

    Iterator<Entry<Integer, String>> it = countries.entrySet().iterator();
    Entry<Integer, String> entry;
    while(it.hasNext())
    {
        entry = it.next();
        System.out.println(entry.getValue() + " " + entry.getKey());            
    }   

这就产生了:

USA 1
India 2
Pakistan 3

-

2)使用未排序的地图并使用比较器进行排序 请参阅:Sort a Map<Key, Value> by values (Java),因为答案很清楚。

- 3)使用带有国家/地区类的ArrayList

为了支持您的示例,您需要创建一个Country类。 您需要执行以下操作:

  1. 在您的国家/地区类中实施Comparable并在此处放置比较逻辑。
  2. 创建一个自定义比较器,您将为其提供Collection.sort调用。

    import java.util.ArrayList; import java.util.Collections; import java.util.InputMismatchException; import java.util.Iterator;

    公共类CountrySortExample {

    public static void main(String[] args) {
        new CountrySortExample();
    }
    
    public ArrayList<Country> countries = new ArrayList<Country>();
    
    public CountrySortExample()
    {
        countries.add(new Country("India",2));
        countries.add(new Country("Pakistan",3));
        countries.add(new Country("USA",1));
    
        Collections.sort(countries);
    
        Iterator<Country> it = countries.iterator();
        Country count;
        while(it.hasNext())
        {
            count = it.next();
            System.out.println(count.CountryName + " " + count.CountryIndex);
        }
    }
    
    class Country implements Comparable
    {
        public String CountryName;
        public int CountryIndex;
    
        public Country(String CountryName,int  CountryIndex )
        {
            this.CountryName = CountryName;
            this.CountryIndex = CountryIndex;
        }
    
        @Override
        public int compareTo(Object o) {
    
            if(! (o instanceof Country))
            throw new InputMismatchException("Country is expected");
    
            Country other = (Country)o;
    
            if(other.CountryIndex > CountryIndex)
            return -1;
    
            else if(other.CountryIndex == CountryIndex)
            return 0;
    
            else return 1;
        }
    }
    

    }

  3. 有关详细信息,请访问:http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

答案 3 :(得分:0)

你可以排序 使用Collections.sort(list,Comparator implementation)

在实现中(这里我使用了匿名实现)覆盖比较方法

你在哪里 获取每个字符串的最后一个字符转换为字符串并比较它们

ArrayList<String> a=new ArrayList<String>();
    a.add("India    2");
    a.add("Pakistan 3");
    a.add("USA      1");
    Collections.sort(a, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            Integer i=Integer.valueOf(o1.substring((o1.length() -1),o1.length()));
            Integer j=Integer.valueOf(o2.substring((o2.length() -1),o2.length()));

            return i.compareTo(j);
        }
    });

你可以乐观代码

答案 4 :(得分:0)

如果您想要以多种方式排序对象,则为要执行的每种排序类型定义Comparator类。

使用OP提供的示例,这是定义对象和比较器的一种方法。

这是一个测试结果:

CountryRating [name=India, rating=2]
CountryRating [name=Pakistan, rating=3]
CountryRating [name=USA, rating=1]

CountryRating [name=USA, rating=1]
CountryRating [name=India, rating=2]
CountryRating [name=Pakistan, rating=3]

以下是示例代码:

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class CountryRating {

    private String  name;

    private int     rating;

    public CountryRating(String name, int rating) {
        this.name = name;
        this.rating = rating;
    }

    public String getName() {
        return name;
    }

    public int getRating() {
        return rating;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        builder.append("CountryRating [name=");
        builder.append(name);
        builder.append(", rating=");
        builder.append(rating);
        builder.append("]");
        return builder.toString();
    }

    public static void main(String[] args) {
        List<CountryRating> list = new ArrayList<CountryRating>();
        CountryRating cr1 = new CountryRating("USA", 1);
        CountryRating cr2 = new CountryRating("India", 2);
        CountryRating cr3 = new CountryRating("Pakistan", 3);
        list.add(cr1);
        list.add(cr2);
        list.add(cr3);

        Collections.sort(list, new CountrySort());
        printList(list);
        System.out.println(" ");
        Collections.sort(list, new RatingSort());
        printList(list);
    }

    private static void printList(List<CountryRating> list) {
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i));
        }
    }

}

class CountrySort implements Comparator<CountryRating> {
    @Override
    public int compare(CountryRating cr1, CountryRating cr2) {
        return cr1.getName().compareTo(cr2.getName());
    }
}

class RatingSort implements Comparator<CountryRating> {
    @Override
    public int compare(CountryRating cr1, CountryRating cr2) {
        return cr1.getRating() - cr2.getRating();
    }
}

答案 5 :(得分:0)

我创建了一个示例,您可以对ArrayList进行排序,即使它包含对象。你可以通读它,看看它是否有帮助。

我已经完成了两个课程和一个测试课程:

头等舱是国家:

public class Country {
   private String countryName;
   private int number;

   public Country(String countryName, int number){
       this.countryName = countryName;
       this.number = number;
   }

   public String getCountryName(){
       return countryName;
   }

   public void setCountryName(String newCountryName){
       countryName = newCountryName;
   }

   public int getNumber(){
       return number;
   }

   public void setNumber(int newNumber){
       number = newNumber;
   }

   public String toString(){
       return getCountryName() + getNumber();
   }
}

下一课是方法:

public class Methods {

    private Country country;
    private ArrayList<Country> overview = new ArrayList<Country>();
    private ArrayList<Country> overviewSorted = new ArrayList<Country>();
    int [] test;

    public void regCountry(String countryname, int numbers){
        if(!(countryname == "" && numbers == 0)){
            overview.add(new Country(countryname, numbers));
        } else {
            System.out.println("The input was null");
        }
    }

    public void showRegisteredCountries(){
        if(!(overview.size() < 0)){
            for(int i = 0; i < overview.size(); i++){
                System.out.println("The country: " + overview.get(i).getCountryName() + " has the number: " + overview.get(i).getNumber() + " registered");
            }
        } else {
            System.out.println("There are no country registered");
        }
    }

    public void numbersOverFromArrayList(){
        if(!(overview.size() < 0)){
            test = new int [overview.size()];
            for(int i = 0; i < overview.size(); i++){
                test[i] = overview.get(i).getNumber();
            }
        }
    }

    public void sortArrayAndCopyItBack(){
        if(!(test.length < 0)){
            java.util.Arrays.sort(test);
            for(int i = 0; i < test.length; i ++){
                for(int j = 0; j < overview.size(); j++){
                    if(test[i] == overview.get(j).getNumber()){
                        overviewSorted.add(new Country(overview.get(j).getCountryName(), overview.get(j).getNumber()));
                    }
                }
            }
        }
    }

    public void showTableSorted(){
        if(!(overviewSorted.size() < 0)){
            for(int i = 0; i < overviewSorted.size(); i++){
                System.out.println("Country name: " +     overviewSorted.get(i).getCountryName() + " with number: " +     overviewSorted.get(i).getNumber());
            }
        } else {
            System.out.println("There are non countrys in table that is sorted");
        }
    }


}

接下来是测试类:

public class test2 {
    public static void main(String [] args){

        Methods methodes = new Methods();

        for(int i = 0; i < 4; i++){
        String inCountry = JOptionPane.showInputDialog("Country:");
        String inNumber = JOptionPane.showInputDialog("number:");
        String country = inCountry;
        int number = Integer.parseInt(inNumber);
        methodes.regCountry(country, number);
        }

        methodes.showRegisteredCountries();
        methodes.numbersOverFromArrayList();
        methodes.sortArrayAndCopyItBack();
        methodes.showTableSorted();
    }
}

我的输出:

The country: Norway has the number: 5 registered
The country: Sweden has the number: 2 registered
The country: Denmark has the number: 9 registered
The country: Finland has the number: 7 registered
Country name: Sweden with number: 2
Country name: Norway with number: 5
Country name: Finland with number: 7
Country name: Denmark with number: 9
相关问题