-3

In this program I sorted strings in Alphabetic way in Simple Array but how can I do the same thing using List or ArrayList, Suppose I have a class Students and I want to order names in an alphabetically way, so how can I do that?

public class CityData{
 public static String citynames[]= {"Hyderabad","Karachi","Abtabad","AzadKashmir"};

    public static void main(String args[]) {
        int size=citynames.length;
        String temp=null;

            for(int i=0; i<size; i++) {
                for(int j=i+1; j<size; j++) {
                    if(citynames[i].compareTo(citynames[j])>0) {
                     temp=citynames[i];
                     citynames[i]=citynames[j];
                     citynames[j]=temp; } 
        } 
                System.out.println(citynames[i]);
      }
    }

 }  

Result:

Abtabad
AzadKashmir
Hyderabad
Karachi
Emma
  • 27,428
  • 11
  • 44
  • 69
  • What issues are you having when trying to do this with lists? – RaminS Aug 02 '19 at 21:16
  • Gendarme nothing wrong with the above code it runs perfectly, but I want to do the same execution in List or ArrayList but I don't know how to call if(citynames[i] in Arraylist or List cause ArrayList and List does not contain square brackets[] and I also tried this syntax if(citynames.get(i) but it still occurs error. – fahad khan Aug 04 '19 at 10:23

3 Answers3

0

I do not have the rights to comment yet, hence adding at as an answer. You can google this easily and also lookup API for sorting collections.

Code in java 8

public class ArrayListSort {
    public static String citynames[] = { "Hyderabad", "Karachi", "Abtabad", "AzadKashmir" };

    public static void main(String args[]) {
        Student stud1 = new Student("Alex", 20);
        Student stud2 = new Student("Bryan", 21);
        Student stud3 = new Student("Chris", 22);
        Student stud4 = new Student("Dan", 23);

        List<Student> students = new ArrayList<>(Arrays.asList(stud4, stud3, stud2, stud1));
        Collections.sort(students);
        for(Student stud: students){
            System.out.println(stud.getName());
        }
    }
}

class Student implements Comparable<Student> {
    private String name;
    private int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return this.name;
    }

    public int getAge() {
        return age;
    }

    @Override
    public int compareTo(Student other) {
        return this.name.compareTo(other.name);

    }
}

Edit 1 to answer your comment, look up Comparable interface

VishRajpal
  • 56
  • 4
  • VishRajpal you are have String class in generic<> but what if you have a class like students which having age and name within it, and you have to sort name alphabetically how we will do that? my problem is how do I do this in ArrayList the issue is not of logic but of syntax. – fahad khan Aug 04 '19 at 10:33
  • Edited answer, look up Comparable interface – VishRajpal Aug 05 '19 at 17:39
0

What you are looking for is actually pretty simple to do:

Instead of using citynames[i] or citynames[j], for Lists and ArrayLists, you use citynames.get(i) or citynames.get(j).

Just think of List.get() is the same as the brackets you put before for the simple arrays.

Just remember, when you want to set a value, you actually have to use the List.set(int index, Object value).

The same can be said if you are trying to get the length of the List or ArrayList. You can simply replace citynames.length to citynames.size();


public static void main(String args[]) {
    int size=citynames.size();
    String temp=null;

        for(int i=0; i<size; i++) {
            for(int j=i+1; j<size; j++) {
                if(citynames.get(i).compareTo(citynames.get(j))>0) {
                 temp=citynames.get(i);
                 citynames.set(i, citynames.get(j));
                 citynames.set(j, temp); } 
    } 
            System.out.println(citynames.get(i));
  }
}

Update: Better Solution:

Note: When using Collections.sort() it is important to make sure the object type of the array implements Comparable. the Collections.sort() uses the compareTo() within the object class to sort the elements.

public class Main(){
import java.util.Collections;
    public static void main(String args[]) {
        ArrayList<City> citynames = new ArrayList<City>();
        citynames.add("Hyderabad");
        citynames.add("Karachi");
        citynames.add("Abtabad");
        citynames.add("AzadKashmir");
        Collections.sort(citynames);
        for(cityname : citynames)
            System.out.println(cityname);
    }
}

public class City implements Comparable{
    private String name;
    // Constructor
    public City(String name){
        this.name = name;
    }

    // Getter method
    public String getName(){
        return name;
    }

    // compareTo Method
    public int compareTo(City other){
        return name.compareTo(other.getName());
    }

    // Other methods may exist
}

For more information: https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

  • FalseStatemnet I tried this solution but still not succeeded. – fahad khan Aug 03 '19 at 19:24
  • Im not sure what you have tried, but I would recommend you to use the Collection.sort method answered above. You would have to make a City class which implements the Comparable interface. This way you can just call the Collection.sort method on your ArrayList or List of City objects to sort it according the whatever you set your compareTo method. – FalseStatement Aug 04 '19 at 05:08
  • FalseStatement this is not working if(citynames.get(i).compareTo(citynames.get(j))>0) { temp=citynames.get(i); citynames.set(i, citynames.get(j)); citynames.set(j, temp); } – fahad khan Aug 04 '19 at 10:39
  • I just added a better solution, pretty much the same answer as the one above, its a better one and I would recommend it. – FalseStatement Aug 04 '19 at 14:18
0

You can sort the collections based on your requirements.

If the input objects for collections is implementing the Comparable interface like String, Integer, Double classes, then you can directly use Collections.sort() method from Collections util class

List<String> al = new ArrayList<>();
    al.add("Hyderabad");
    al.add("Karachi");
    al.add("Abtabad");
    al.add("AzadKashmir");
    al.add("Udupi");
    al.add("Jammu");

    Collections.sort(al);

Or you can sort the list based on your requirement.(Reverse alphabetical Order)

Collections.sort(al, (str1, str2) -> str2.compareTo(str1));

If you don't want to use the Collections class, then directly use the sort() method present in List interface.

i. Albhabetical Order

al.sort((str1, str2) -> str1.compareTo(str1));

ii. Reverse Albhabetical Order

al.sort((str1, str2) -> str2.compareTo(str1));

The above solution is for the Objects where the class implements the Comparable Interface like String, Integer, Double, etc...

When to sort the Custom Classes, you need to implement sort by Comparator class or Lambda expression for the Comparator.

Consider you have a Student Class, and need to sort by city names. You can use below code.

Student Class

public class Student {
    private String name;
    private String city;

    public Student() {}

    public Student(String name, String city) {
        this.name = name;
        this.city = city;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "Student -> [name=" + name + ", city=" + city + "]";
    }
}

Sorting By Collection Class sort() method

Student st1 = new Student("Samir", "Hyderabad");
Student st2 = new Student("Akbar", "Karachi");
Student st3 = new Student("Ramu", "Abtabad");
Student st4 = new Student("Rahim", "AzadKashmir");
Student st5 = new Student("Sardar", "Udupi");
Student st6 = new Student("Fahad khan", "Jammu");

List<Student> al2 = new ArrayList<>();
al2.add(st1);
al2.add(st2);
al2.add(st3);
al2.add(st4);
al2.add(st5);
al2.add(st6);

//Alphabetical Order
Collections.sort(al2, (std1, std2) -> std1.getCity().compareTo(std2.getCity()));

//Reverse Alphabetical Order
Collections.sort(al2, (std1, std2) -> std2.getCity().compareTo(std1.getCity()));

By using List.sort() method

//Alphabetical Order
al2.sort((std1, std2) -> std1.getCity().compareTo(std2.getCity()));

//Reverse Alphabetical Order
al2.sort((std1, std2) -> std1.getCity().compareTo(std2.getCity()));
Manjunath H M
  • 818
  • 1
  • 10
  • 25