0

ArrayList我正在寻找<String,int>根据int.

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

India    2
Pakistan 3
USA      1

输出变为:

USA      1
India    2
Pakistan 3

我很困惑它如何与 int 一起工作。Collections.sort(var)不适用于它。

4

6 回答 6

4

您不能使用 ArrayList 类型

 <String, int>
  1. ArrayList 中不能有原语,因为 ArrayList 包含对象。因此,您可以做的最接近的是存储 Integer 对象。
  2. 如果要对其进行参数化,则 ArrayList 只能是一种类型。

如果要保存 String 和 int,可以创建一个 CountryInfo 类,其中包含字段名称和排名。然后创建

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

然后你可以使用

  Collections.sort(list, <Comparator>)
于 2013-04-09T17:38:15.710 回答
0

那不是 ArrayList。代替使用 TreeMap。

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

这样会自动排序

于 2013-04-09T17:44:46.680 回答
0

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

因此,有三种选择:

1.利用一个同时包含Key和Map的TreeMap,并自动按key排序

2. 使用未排序的映射并使用比较器进行排序 - 请参阅Sort a Map<Key, Value> by values (Java)

3. 使用带有比较器的自定义类的数组列表。

-

1) 使用树形图

树图是红黑树的一种实现。请参阅: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)利用未排序的映射并使用比较器进行排序 请参阅:按值排序 Map<Key, Value>(Java),因为答案很容易写。

- 3) 使用带有 Country 类的 ArrayList

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

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

    导入 java.util.ArrayList;导入 java.util.Collections;导入 java.util.InputMismatchException;导入 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;
        }
    }
    

    }

更多信息请访问:http ://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

于 2013-04-09T17:49:27.307 回答
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);
        }
    });

你可以乐观代码

于 2013-04-09T17:50:01.940 回答
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();
    }
}
于 2013-04-09T18:33:04.183 回答
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
于 2013-04-09T18:42:27.720 回答