【问题标题】:ArrayList sort for String, int [duplicate]String,int的ArrayList排序[重复]
【发布时间】:2013-04-09 17:32:44
【问题描述】:

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

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

India    2
Pakistan 3
USA      1

输出变成:

USA      1
India    2
Pakistan 3

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

【问题讨论】:

  • Collections.sort(var, Comparator)
  • 为您的班级实施Comparator 并致电Collections.sort(var, comparator);
  • 您不想使用SortedMap 实现吗?
  • @Tom OP 使用的是 ArrayList,而不是 Map
  • ArrayList<String,int> 是什么?会不会是Map<String, Integer>

标签: java arrays collections arraylist


【解决方案1】:

你不能使用 ArrayList 类型的

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

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

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

然后就可以使用了

  Collections.sort(list, <Comparator>)

【讨论】:

  • 看起来像一个包含 Stringint 属性的类,但 OP 不知道其他方式。
【解决方案2】:

我创建了一个示例,您可以在其中对 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

【讨论】:

    【解决方案3】:

    这不是一个 ArrayList。改为使用 TreeMap。

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

    这样会自动排序

    【讨论】:

    • 虽然它可能是暗示的,但 OP 从未真正声明该字符串是唯一的,因此地图甚至可能不适合他。
    • 也可能是Map&lt;Integer, String&gt;,所以我们永远不知道...
    【解决方案4】:

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

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

    你在哪里 将每个字符串的最后一个字符转换为字符串并进行比较

    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);
            }
        });
    

    你可以优化代码

    【讨论】:

    • 你的意思是你可以改进代码
    • yaa 代码可以进一步改进:)
    • 使用子字符串似乎效率低下。此外,您强制为国家/地区设置特定的最大大小,或者必须使用其他方法,例如 indexOf、substring 等。
    • 没有固定国家/地区的最大尺寸。根据他的例子,我假设最后一个字符是整数。取出你可以排序的最后一个字符。 .当然你可以修改它并使用正则表达式提取整数部分然后使用 compareTo
    【解决方案5】:

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

    因此,有三种选择:

    1.使用同时包含 Key 和 Map 并按 key 自动排序的 TreeMap

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

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

    -

    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) 使用带有 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/

    【讨论】:

      【解决方案6】:

      如果您想要以多种方式对对象进行排序,则可以为每种要执行的排序类型定义一个 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();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-04-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-01
        • 2021-11-04
        • 2016-06-26
        相关资源
        最近更新 更多