1

Can collection.sort display output in descending order leaving the character in same place? eg. Input=100,200,a,300 Output=300,200,a,100. I am using Arraylist which is String type.

String input = JOptionPane.showInputDialog("Enter a string:"); 
String[] abc = input.split(",");
ArrayList<String> num = new ArrayList<String>();
for (int i = 0; i < abc.length; i++)
{
    num.add(abc[i]);
}
Collections.sort(num, Collections.reverseOrder());
System.out.println(num);
3
  • 2
    No. You will need to create your own Comparator. Commented Mar 23, 2015 at 7:18
  • 1
    That looks like a XY problem; one thing is sure, you can't use Collections.sort() for that. Commented Mar 23, 2015 at 7:18
  • Here i have tried using bubble shot, but i dont khow what is wrong. stackoverflow.com/questions/29148652/bubble-sort-in-arraylist Commented Mar 23, 2015 at 7:21

3 Answers 3

1

One can use Collections.reverseOrder() comparator to sort the list in reverse order.

public class CollectionsDemo {
public static void main(String args[]) {  
  // create linked list object         
  LinkedList list = new LinkedList();  

  // populate the list 
  list.add(-28);  
  list.add(20);  
  list.add(-12);  
  list.add(8);  

  // create comparator for reverse order
  Comparator cmp = Collections.reverseOrder();  

  // sort the list
  Collections.sort(list, cmp);  

  System.out.println("List sorted in ReverseOrder: ");      
  for(int i : list){
     System.out.println(i+ " ");
  } 
  }
  }
Sign up to request clarification or add additional context in comments.

Comments

1

You may try to create your own comparator like this:

static <K,V extends Comparable<? super V>> 
            List<Entry<K, V>> reverseSortValues(Map<K,V> map) 
{

    List<Entry<K,V>> lst = new ArrayList<Entry<K,V>>(map.entrySet());

    Collections.sort(lst, 
            new Comparator<Entry<K,V>>() 
            {
                @Override
                public int compare(Entry<K,V> e1, Entry<K,V> e2) 
                {
                    return e2.getValue().compareTo(e1.getValue());
                }
            }
    );

    return lst;
}

Comments

0

Create comparator for reverse order -

Comparator cmp = Collections.reverseOrder();  

Then sort the list -

Collections.sort(num, cmp);    

The Collections.reverseOrder() is used to get a Comparator that reverses the natural ordering.

Comments

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.