Java collection.sort如何以相反的顺序显示输出?

Java collection.sort如何以相反的顺序显示输出?,java,Java,collection.sort是否可以按降序显示输出,将字符保留在同一位置?例如,输入=100200,a,300输出=300200,a,100。 我使用的是字符串类型的Arraylist String input = JOptionPane.showInputDialog("Enter a string:"); String[] abc = input.split(","); ArrayList<String> num = new ArrayList<String>()

collection.sort是否可以按降序显示输出,将字符保留在同一位置?例如,输入=100200,a,300输出=300200,a,100。 我使用的是字符串类型的Arraylist

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);
String input=JOptionPane.showInputDialog(“输入字符串:”);
字符串[]abc=input.split(“,”);
ArrayList num=新的ArrayList();
for(int i=0;i
为逆序创建比较器-

Comparator cmp = Collections.reverseOrder();  
然后对列表进行排序-

Collections.sort(num, cmp);    

Collections.reverseOrder()
用于获取一个反向自然排序的
比较器

您可以尝试创建自己的比较器,如下所示:

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;
}

static可以使用Collections.reverseOrder()比较器对列表进行反向排序

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+ " ");
  } 
  }
  }

不需要。您需要创建自己的比较器。这看起来像是XY问题;有一件事是肯定的,你不能用
Collections.sort()
来做这件事。在这里,我尝试过使用bubble shot,但我不知道有什么问题。