30

I have to create a method that sorts an ArrayList of objects alphabetically according to email and then prints the sorted array. The part that I am having trouble with it sorting it. I have researched it and tried using Collections.sort(vehiclearray); but that didn't work for me. I was that I needed something called a comparator but couldn't figure out how it worked. Will I have to use those or can something like bubble sort or insertion sort work for this kind of thing?

This is the code that I have so far:

public static void printallsort(ArrayList<vehicle> vehiclearray){

   ArrayList<vehicle> vehiclearraysort = new ArrayList<vehicle>();
   vehiclearraysort.addAll(vehiclearray);

 //Sort
   for(int i = 0; i < vehiclearraysort.size(); i++) 
   if ( vehiclearray.get(i).getEmail() > vehiclearray.get(i+1).getEmail())

//Printing 
   for(i = 0; i < vehiclearraysort.size(); i++)           
   System.out.println( vehiclearraysort.get(i).toString() + "\n");

}
4
  • 3
    No, you need a comparator. What didn't work about it? Commented Oct 19, 2013 at 20:52
  • 2
    Please follow Java naming conventions: Vehicle instead of vehicle. And probably printAllSort and vehicleArraySort. Commented Oct 19, 2013 at 20:52
  • 1
    There is a lot of tutorials which explains how to implement a comparator for your classes. Try to check this one first : docs.oracle.com/javase/tutorial/collections/interfaces/… Commented Oct 19, 2013 at 20:54
  • @arshajii is right. Read this: Code Conventions for the Java Programming Language. Commented Oct 19, 2013 at 21:13

5 Answers 5

97

The sorting part can be done by implementing a custom Comparator<Vehicle>.

Collections.sort(vehiclearray, new Comparator<Vehicle>() {
    public int compare(Vehicle v1, Vehicle v2) {
        return v1.getEmail().compareTo(v2.getEmail());
    }
});

This anonymous class will be used for sorting the Vehicle objects in the ArrayList on the base of their corresponding emails alphabetically.

Upgrading to Java8 will let you also implement this in a less verbose manner with a method reference:

Collections.sort(vehiclearray, Comparator.comparing(Vehicle::getEmail));
Sign up to request clarification or add additional context in comments.

Comments

14

Although the question already has an accepted answer I would like to share some Java 8 solution

// if you only want to sort the list of Vehicles on their email address
Collections.sort(list, (p1, p2) -> p1.getEmail().compareTo(p2.getEmail()));

.

// sort the Vehicles in a Stream
list.stream().sorted((p1, p2) -> p1.getEmail().compareTo(p2.getEmail()));

.

// sort and print with a Stream in one go
list.stream().sorted((p1, p2) -> p1.getEmail().compareTo(p2.getEmail())).forEach(p -> System.out.printf("%s%n", p));

.

// sort with an Comparator (thanks @Philipp)
// for the list
Collections.sort(list, Comparator.comparing(Vehicle::getEmail));
// for the Stream
list.stream().sorted(Comparator.comparing(Vehicle::getEmail)).forEach(p -> System.out.printf("%s%n", p));

1 Comment

I think this can be simplified using Comparator.comparing: docs.oracle.com/javase/8/docs/api/java/util/…
0

In this link you can find code which will help you to sort arraylist of objects in descending and ascending order.

http://beginnersbook.com/2013/12/java-arraylist-of-object-sort-example-comparable-and-comparator/

1 Comment

you have added a less informative answer to a question which has already accepted answer and is better also
0

package srikanthdukuntla;

import java.util.ArrayList; import java.util.List;

public class AlphabetsOrder {

public static void main(String[] args) {

    String temp;
    List<String> str= new ArrayList<String>();

    str.add("Apple");
    str.add("zebra");
    str.add("Umberalla");
    str.add("banana");
    str.add("oxo");
    str.add("dakuntla");
    str.add("srikanthdukuntla");
    str.add("Dukuntla");

    for(int i=0;i<str.size();i++){

        for(int j=i+1;j<str.size();j++){

     if(str.get(i).compareTo(str.get(j))<0){

            temp=str.get(i);
            str.set(i, str.get(j));
            str.set(j,temp );   

     }
        }
    }

  System.out.println("List of words in alphabetical order   "+str);

}

}

Comments

0

clearest

vehiclearray.sort(Comparator.comparing(Vehicle::getEmail()));

1 Comment

Can you explain your answer a little more?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.