Results 1 to 13 of 13
  1. #1
    casta is offline Member
    Join Date
    Apr 2016
    Posts
    27
    Rep Power
    0

    Default How to sort arraylist on variable values

    Hi guys. I have a question concerning my arraylist. I want my application to import a text file with a list of arders and then sort on the startTime variable.
    What my test case looks like currently:

    The text file:
    1 a b 11:00
    2 a b 11:30
    3 a b 10:00
    The classes I am working with at the moment are: Arder.class and the class with the main method.
    The arder class:
    Java Code:
    public class Arder {
    	int arderID;
    	LocalTime startTime;
    
    	public Arder(String line) {
    		String[] arrayLine = line.split("\\s+");
    		this.arderID = Integer.parseInt(arrayLine[0]);
    		this.startTime = LocalTime.parse(arrayLine[3]);
    
    	}
    	public String toString() { 
    
    		return "ID "+  arderID + " with start time " + startTime; 
    		}
    	
    	public String getArdersByTime(){ //My attempt to make something work with comparing
    		return "Start time = " + startTime; //To see whether the arrayList is correctly sorted
    	};
    The class with the main method:
    Java Code:
    	    ArrayList<Arder> oardersUnassigned = new ArrayList<Arder>();
    	    try {
    	        File myFile2 = new File("src/arders.txt");
    	        FileReader fileReader2 = new FileReader(myFile2);
    	        BufferedReader reader2 = new BufferedReader(fileReader2);
    	        String line2 = null;
    	        while ((line2 = reader2.readLine()) != null) { 
    	        	ardersUnassigned.add( new Arder(line2) );
    	    }
    	    reader2.close();
    	    } catch(NumberFormatException nfe){ 
    	    	System.out.println("OOPS");
    	    	nfe.printStackTrace(); 
    	    } catch(Exception ex) { 
    	    	ex.printStackTrace();
    	    } //end reading
    
    		Collections.sort(ardersUnassigned, new Comparator<Arder>(){
    			@Override public LocalTime compare(Arder o1, Arder o2) { //Think o1 and o2 are inappropriate either way, since I have not given them these reference variable names
    				return o1.startTime - o2.startTime;
    			}
    		}
    I found the code Collections.sort(......) above from several pages (e.g. java - How to sort an arraylist of objects by a property? - Stack Overflow) , but I was not able to convert it to my situation. When I look at the formulation of this method, it seems like there is a fixed number of arders, while I have a variable number of arders. Can somebody help me out?
    Last edited by casta; 04-28-2016 at 04:40 PM.

  2. #2
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: How to sort arraylist on variable values

    What errors are you getting with the current code?

    The structure of your Comparator (apart from the return type) is correct.
    It should return an int.

    It is used by the sort method to determine whether one Order is before or after another Order, hence the two parameters.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  3. #3
    Pavlo is offline Member
    Join Date
    Dec 2012
    Posts
    28
    Rep Power
    0

    Default Re: How to sort arraylist on variable values

    Hello.

    Something not clear with your question. ;) What you mean when state:

    When I look at the formulation of this method, it seems like there is a fixed number of orders, while I have a variable number of orders.

    Method sort, not have any limit on list size. And what you mean your list have variable number of orders? When you call Collections.sort your list size not changes. I'm just curious are you checked ordersUnassigned list filled with data? I mean list size and Order objects?

    And one more: Please use compareTo method of LocalTime object, instead of

    Java Code:
    o1.startTime - o2.startTime;
    so it will look like:

    Java Code:
    o1.startTime.compareTo(o2.startTime);

    https://docs.oracle.com/javase/8/doc...ime.LocalTime-

  4. #4
    casta is offline Member
    Join Date
    Apr 2016
    Posts
    27
    Rep Power
    0

    Default Re: How to sort arraylist on variable values

    Exception in thread "main" java.lang.Error: Unresolved compilation problems:
    The method sort(List<T>, Comparator<? super T>) in the type Collections is not applicable for the arguments (ArrayList<Arder>, new Comparator<Arder>(){})
    Comparator cannot be resolved to a type
    The method compare(Arder, Arder) of type new Comparator<Arder>(){} must override or implement a supertype method
    startTime cannot be resolved or is not a field
    startTime cannot be resolved or is not a field
    Syntax error, insert ")" to complete MethodInvocation
    Syntax error, insert ";" to complete Statement

    is the error I get when I use the next code:
    Java Code:
    		Collections.sort(ardersUnassigned, new Comparator<Arder>(){
    			@Override public LocalTime compare(Arder o1, Arder o2) { //Think o1 and o2 are inappropriate either way, since I have not given them these names
    				return o1.startTime.compareTo(o2.startTime);
    			}
    		}
    A change to int does not solve problems either. I get the exact same error
    Last edited by casta; 04-28-2016 at 04:41 PM.

  5. #5
    casta is offline Member
    Join Date
    Apr 2016
    Posts
    27
    Rep Power
    0

    Default Re: How to sort arraylist on variable values

    @pavlo,

    I want to run the sorting process at several stages. What I meant with a variable amount of arders is that the number of arders may differ per method invocation.
    I may start with 10 arders. Later on, I want to use the same sorting step for 4 arders.
    Last edited by casta; 04-28-2016 at 04:41 PM.

  6. #6
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: How to sort arraylist on variable values

    The method returns an int.

    If that still gives an error (and you really shouldn't bother trying to run code that doesn't compile) then you're possibly not actually importing Comparator, or it hasn't compiled for some other reason.

    The sort method doesn't care how many entries are in the List its been given, so the number of Orders is not important.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  7. #7
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: How to sort arraylist on variable values

    You are missing a closing ); (see last two errors).

    A change to int does not solve problems either. I get the exact same error
    Then you have a different problem (probably the syntax. Leave it as an int).

    Regards,
    Jim
    Last edited by jim829; 04-28-2016 at 03:50 PM.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

  8. #8
    casta is offline Member
    Join Date
    Apr 2016
    Posts
    27
    Rep Power
    0

    Default Re: How to sort arraylist on variable values

    Thank you guys. I may blame myself for not importing the Comparator in the first place. Furthermore, indeed placing a ) and a semicolon did the trick.
    Java Code:
    Collections.sort(ardersUnassigned, new Comparator<Arder>(){
    			@Override public int compare(Arder o1, Arder o2) { 
    				return o1.startTime.compareTo(o2.startTime);
    			}
    		});
    Last edited by casta; 04-28-2016 at 04:42 PM.

  9. #9
    casta is offline Member
    Join Date
    Apr 2016
    Posts
    27
    Rep Power
    0

    Default Re: How to sort arraylist on variable values

    How would I be able to sort on two (or more variables)?
    So, the first comparison would be time, the second a prioritynumber?

    I have found several answers on the internet, but I am a bit confused. For instance:
    Java Code:
    public class FooComparator implements Comparator<Foo> {
        public int compare(Foo a, Foo b) {
            int dateComparison = a.date.compareTo(b.date);
            return dateComparison == 0 ? a.value.compareTo(b.value) : dateComparison;
        }
    }
    
    Collections.sort(foos, new FooComparator());
    Makes use of a class called FooComparator. Am I obliged to use a new class when I sort on 2 variables? If so, how can I refer to it in the class with my main method?

  10. #10
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    26

    Default Re: How to sort arraylist on variable values

    You already have a new Comparator class. In your case it has no name (otherwise known as an anonymous class).

    All you need to do is expand on the criteria used in your compare() method.

    Java Code:
    int result = o1.startTime.compareTo(o2.startTime);
    return result == 0 ? o1.someOtherVariable.compareTo(o2.someOtherVariable) : result;
    Something like that.
    You can have a whole chain of them if needed.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  11. #11
    casta is offline Member
    Join Date
    Apr 2016
    Posts
    27
    Rep Power
    0

    Default Re: How to sort arraylist on variable values

    O wow. That was easy. Thank you very much!

  12. #12
    Zerkum is offline Member
    Join Date
    May 2016
    Location
    South Africa
    Posts
    1
    Rep Power
    0

    Default Re: How to sort arraylist on variable values

    Is this important?
    In line 1 of the code for the class with the main method you use oardersUnassigned, while in lines 8 and 18 you use ardersUnassigned. I'm very new to Java, but this looks like a coding typo.

  13. #13
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    13

    Default Re: How to sort arraylist on variable values

    Quote Originally Posted by Zerkum View Post
    Is this important?
    In line 1 of the code for the class with the main method you use oardersUnassigned, while in lines 8 and 18 you use ardersUnassigned. I'm very new to Java, but this looks like a coding typo.
    It does indeed look like an error. Could have been a pasting error, or perhaps ardersUnassigned was declared somewhere else not shown. Since the OP
    successfully ran the program I presume it was found (the compiler would have flagged an undeclared value). If it were unassigned an exception would have
    been thrown.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Sort an ArrayList
    By überfuzz in forum New To Java
    Replies: 13
    Last Post: 02-10-2011, 01:18 PM
  2. How to pu a sort of Global Variable?
    By esgol in forum New To Java
    Replies: 3
    Last Post: 01-19-2011, 05:46 PM
  3. ArrayList sort
    By Dipke in forum New To Java
    Replies: 1
    Last Post: 08-23-2010, 01:01 PM
  4. how to sort an arraylist?
    By zhangster in forum New To Java
    Replies: 5
    Last Post: 03-19-2010, 08:01 AM
  5. Using Merge Sort to sort an ArrayList of Strings
    By coldfire in forum New To Java
    Replies: 3
    Last Post: 03-13-2009, 01:03 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •