0

I m looking to sort an ArrayList which is of the type <String,int>, according to int.

So, my variable is var<String,int>

India    2
Pakistan 3
USA      1

The output becomes:

USA      1
India    2
Pakistan 3

I am confused how does it works with int. Collections.sort(var) does not works with it.

Luiggi Mendoza
  • 85,076
  • 16
  • 154
  • 332
user1141584
  • 619
  • 5
  • 16
  • 29
  • 3
    Look at `Collections.sort(var, Comparator)` – Keppil Apr 09 '13 at 17:34
  • Implement a `Comparator` for your class and call `Collections.sort(var, comparator);` – Luiggi Mendoza Apr 09 '13 at 17:34
  • 1
    Wouldn't you rather use a [SortedMap](http://docs.oracle.com/javase/6/docs/api/java/util/SortedMap.html) implementation? – toniedzwiedz Apr 09 '13 at 17:36
  • 1
    @Tom OP's using `ArrayList`, not `Map`. – Luiggi Mendoza Apr 09 '13 at 17:36
  • What's `ArrayList`? Could it be `Map`? – Saintali Apr 09 '13 at 17:37
  • @LuiggiMendoza how could I know what he's using? The post above is pure pseudocode. I merely suggested an interface that should do the job described. – toniedzwiedz Apr 09 '13 at 17:42
  • @Tom we should lead to OP to the right path. This looks like a misconception of `ArrayList` type (since it can't adopt a pair ``), but being strict the map solution would be using `TreeMap`. Still, this looks more like a class which contains `String` and `int` attributes inside it (or a since OP claims this as `var` which is still wrong because it should be `var`). – Luiggi Mendoza Apr 09 '13 at 17:45
  • I've gone through all 3 options that could use to take care of the specific problem. The problem could better be described with something such as: "How do we store and sort pairs of variables using the Sort java method." – Menelaos Apr 09 '13 at 18:20

6 Answers6

4

You can't use ArrayList of type

 <String, int>
  1. You can't have primitives in ArrayList as ArrayList holds objects. So, the closest you can do is to store Integer objects.
  2. ArrayList can be of only one type if you are parameterizing it.

If you want to hold String and int, you can create a class CountryInfo with fields name and rank. Then create

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

Then you can use

  Collections.sort(list, <Comparator>)
IndoKnight
  • 1,846
  • 1
  • 21
  • 29
0

That is not an ArrayList. Use TreeMap in Stead.

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

This way it will be sorted automatically

Seid.M
  • 185
  • 7
0

ArrayList is a collection of one type of object. It is not like maps that can take two inputs.

Therefore, there are three options:

1. Make use of a TreeMap that contains both a Key and a Map and is automatically sorted by key or

2. Make use of an unsorted map and sort with a comparator - see Sort a Map<Key, Value> by values (Java) or

3. Use an arraylist of a custom class with a comparator.

-

1) Using a TreeMap

Treemaps are an implementation of red-black trees. See: 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());            
    }   

And this Produces:

USA 1
India 2
Pakistan 3

-

2) Make use of an unsorted map and sort with a comparator See: Sort a Map<Key, Value> by values (Java) as the answer is very will written.

- 3) Using an ArrayList with Country Class

In order to support your example you would need to create a Country class. You would need to do the following:

  1. Implement Comparable within your country class and place the logic for the comparison within there.
  2. Create a custom comparator that you will give to your Collection.sort invocation.

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

    public class 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;
        }
    }
    

    }

Further information is available at: http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/

Community
  • 1
  • 1
Menelaos
  • 23,508
  • 18
  • 90
  • 155
0

You can sort
use Collections.sort(list,Comparator implementation)

in the implementation(here I have used anonymous implementation) override compare method

where you get last character of each string convert to string and compare them

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

You can optimist code

Nirbhay Mishra
  • 1,629
  • 3
  • 19
  • 35
  • You mean *you can improve the code* – Luiggi Mendoza Apr 09 '13 at 17:50
  • yaa code can be further improved :) – Nirbhay Mishra Apr 09 '13 at 17:52
  • using sub string seems inefficient. Also, you force a specific max size for country or have to use additional methods such as indexOf, substring, etc. – Menelaos Apr 09 '13 at 18:18
  • there is no maximum size for country fixed. As per his examples I am assuming that last character is Integer. taking out that last character you can sort. . Of course you can modify it and use regular expressions to extract integer part and then use compareTo – Nirbhay Mishra Apr 09 '13 at 18:27
0

If you have an object that you want to sort in more than one way, you define a Comparator class for each type of sort you want to do.

Using the example that the OP gave, here's one way to define the object and Comparators.

Here's one test result:

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]

And here's the example code:

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();
    }
}
Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
0

I have created an example where you can sort your ArrayList even if its with objects. You can read through it an see if it's helps.

I have made two classes and a test class:

First class is Country:

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

Next class is Methods:

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


}

Next is the test class:

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

My output:

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
CronbachAlpha
  • 355
  • 1
  • 5
  • 14