Results 1 to 6 of 6
Like Tree2Likes
  • 1 Post By gozzy
  • 1 Post By jim829

Thread: Sort multidimensional list by the last element

  1. #1
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Sort multidimensional list by the last element

    Hi.

    I have a multidimensional list (List<List<String>>) that has these kinds of values:

    [["a1","a2","a3","25"],["b1","b2","b3","12"],["c1","c2","c3","20"]]

    I would like to sort the inner arrays by the last elements, i.e.

    [["b1","b2","b3","12"],["c1","c2","c3","20"],["a1","a2","a3","25"]]

    What would be the best way to do it?

    Thanks a lot!

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

    Default Re: Sort multidimensional list by the last element

    The easiest way is to create an instance of the Comparator functional interface and pass it to the Collections.sort() method along with your array.

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

  3. #3
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: Sort multidimensional list by the last element

    jim829. Thank you for the hint. Did you mean somethings like this?

    Java Code:
    List<List<String>> listNavDataUnsorted = new ArrayList<List<String>>();
    
    listNavDataUnsorted = fillTheList();
    
    Comparator<String> defaultComparator = new Comparator<String>() 
    {
         @Override
         public int compare(String o1, String o2) 
        {
              return o1.compareTo(o2);
        }
     }; 
                    
    Collections.sort(listNavDataUnsorted.get(listNavDataUnsorted.size()-1), defaultComparator);
    Thank you!

  4. #4
    gozzy is offline Member
    Join Date
    Jan 2017
    Posts
    46
    Rep Power
    0

    Default Re: Sort multidimensional list by the last element

    I have a multidimensional list (List<List<String>>) that has these kinds of values:
    I would like to sort the inner arrays by the last elements, i.e.
    Which is it: String[] or List<String>?
    If it's the latter, try

    Java Code:
    	Comparator<List<String>> lastElementComparator = new Comparator<List<String>>() 
    	{
    	    @Override
    	    public int compare(List<String> list1, List<String> list2) 
    	    {
    		return Integer.compare(Integer.valueOf(list1.get(list1.size()-1)),
    			Integer.valueOf(list2.get(list2.size()-1)));
    	    }
    	};
    Last edited by gozzy; 04-24-2017 at 11:04 AM.
    igorland likes this.

  5. #5
    igorland is offline Member
    Join Date
    Jan 2013
    Posts
    89
    Rep Power
    0

    Default Re: Sort multidimensional list by the last element

    Thanks a lot, gozzy!

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

    Default Re: Sort multidimensional list by the last element

    This presumes you may use the built-in Collections.sort method. Neither the tutorials nor
    the JDK API provide very good examples of how to use this (or the examples may be hard to
    find, so here is a tutorial on sorting).

    Java Code:
    import java.util.Collections;
    import java.util.Comparator;
    import java.util.List;
    import java.util.Random;
    import java.util.stream.Collectors;
    
    public class SortDemo {
    
       static Random r = new Random();
       public static void main(String[] args) {
         // create a list of size 7 of values between 1 and 100 inclusive
         List<Integer> ints = r.ints(7, 1, 101).boxed().collect(Collectors.toList()); 
         
         // Because the Integer class implements the Comparable interface it can always
         // sort on its natural ordering (which is decided by the implementer).  In this
         // case, ascending order.  It is done by calling a.compareTo(b) for each element
         // that is in the list.
         
         System.out.println(ints);
         Collections.sort(ints);
         System.out.println(ints);
         System.out.println("-----------------------------");
         
         // If I want to sort in descending order I could do it like this.
         
         Comparator<Integer> descendingSort = (a,b)->b.compareTo(a);
         Collections.sort(ints, descendingSort);
         System.out.println(ints);
         System.out.println("-----------------------------");
         
         // All I did was use the natural order comparator and reverse how the elements
         // are used.  b.compareTo(a)  vs a.compareTo(b).
         // Using a Comparator simply provides a way to sort other than the natural ordering
         // and that is its intended purprose.  The natural ordering is done by having the List elements
         // implement the Comparable interface.  String, Integer, etc all implement the Comparable
         // interface in such a way as to reflect their natural ordering.
    
         
         // I could also have done it like this.
         
         ints = r.ints(7, 1, 101).boxed().collect(Collectors.toList());
         descendingSort = (a,b) -> b > a ? 1 : a > b ? -1 : 0;
         Collections.sort(ints,descendingSort);
         System.out.println(ints);
         System.out.println("-----------------------------");
         
         // In the previous examples, I have been using Lambda expressions.  They don't have
         // to be used and can add additional complexity to get the actual task done if
         // you aren't familiar with them.  So just use a typical interface implementation or
         // an anomymous class
         
         //One more time to init list
         ints = r.ints(7, 1, 101).boxed().collect(Collectors.toList());
         System.out.println(ints);
         Collections.sort(ints,new newDescendingSort());
         System.out.println(ints);
        
         
         
       }
       static class newDescendingSort implements Comparator<Integer> {
            public int compare(Integer a, Integer b) {
               if (b > a) {
                  return 1;
               }
               if (a > b) {
                  return -1;
               }
               return 0;
            }
         }
    
    }
    Your job is to understand that you are sorting on a list of lists where the sorting is based on the last element of
    each list in the main list. Using my example above and the JDK API, try and develop the code. We will be here to help.

    Regards,
    Jim
    Last edited by jim829; 04-25-2017 at 02:13 AM. Reason: grammar
    igorland likes this.
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. How to pop the element of stack to a list?
    By hjxlpp in forum Advanced Java
    Replies: 3
    Last Post: 07-14-2013, 01:10 PM
  2. last element of recursive list
    By rokko in forum New To Java
    Replies: 21
    Last Post: 04-02-2012, 05:14 PM
  3. how to compare multidimensional list elements
    By srinivasmallabathula in forum Advanced Java
    Replies: 1
    Last Post: 09-09-2011, 10:54 AM
  4. Replies: 4
    Last Post: 02-21-2011, 09:34 AM
  5. How to sort a list using Bubble sort algorithm
    By Java Tip in forum Algorithms
    Replies: 3
    Last Post: 04-29-2008, 08:04 PM

Tags for this Thread

Posting Permissions

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