记录一些Java排序常用到的方法
注意:使用封装数据类型而不是基本数据类型
public class _JavaArrays排序 {
public static void main(String[] args) {
Integer[] aIntegers = {9,5,2,6,7,1,0,3,4,8};
Arrays.sort(aIntegers, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
// TODO Auto-generated method stub
return o2-o1;
}
});
System.out.println(Arrays.toString(aIntegers));
}
}
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
public class _Java排序lambda表达式 {
public static void main(String[] args) {
Integer[] aIntegers = {9,5,2,6,7,1,0,3,4,8};
Arrays.sort(aIntegers, (o1,o2)->o2-o1);
System.out.println(Arrays.toString(aIntegers));
Arrays.sort(aIntegers, (o1,o2)->o1-o2);
System.out.println(Arrays.toString(aIntegers));
}
}
[9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
public static void main(String[] args) {
PriorityQueue<Integer> queue = new PriorityQueue<>((o1,o2)->o1-o2);
queue.offer(5);
queue.offer(1);
queue.offer(4);
queue.offer(6);
queue.offer(2);
queue.offer(8);
queue.offer(3);
System.out.println(queue);
}
[1, 2, 3, 6, 5, 8, 4]
public class _Java排序Collections翻转 {
public static void main(String[] args) {
Integer[] aIntegers = {5,3,6,9,8,1,2,4,7};
List<Integer> asList = Arrays.asList(aIntegers);
Collections.reverse(asList);
System.out.println(asList.toString());
}
}
[7, 4, 2, 1, 8, 9, 6, 3, 5]
public class _Collections排序 {
public static void main(String[] args) {
Integer[] aIntegers = {5,3,6,9,8,1,2,4,7};
List<Integer> asList = Arrays.asList(aIntegers);
Collections.sort(asList);
System.out.println(asList.toString());
Collections.sort(asList,(o1,o2)->o2-o1);
System.out.println(asList.toString());
}
}
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 8, 7, 6, 5, 4, 3, 2, 1]
public class _treeMap按key排序 {
public static void main(String[] args) {
TreeMap<Integer, Integer> map = new TreeMap<>();
map.put(1, 2);
map.put(3, 1);
map.put(2, 7);
map.put(6, 5);
map.put(4, 3);
map.put(6, 4);
map.put(7, 8);
System.out.println(map.toString());
}
}
//默认按照key来进行排序,底层为红黑树
{1=2, 2=7, 3=1, 4=3, 6=4, 7=8}
public class _treeMap按key排序 {
public static void main(String[] args) {
TreeMap<Integer, Integer> map = new TreeMap<>((o1,o2)->o2-o1);
map.put(1, 2);
map.put(3, 1);
map.put(2, 7);
map.put(6, 5);
map.put(4, 3);
map.put(6, 4);
map.put(7, 8);
System.out.println(map.toString());
}
}
{7=8, 6=4, 4=3, 3=1, 2=7, 1=2}
public class _treeMap按value排序 {
public static void main(String[] args) {
TreeMap<Integer, Integer> map = new TreeMap<>();
map.put(1, 2);
map.put(3, 1);
map.put(2, 7);
map.put(6, 5);
map.put(4, 3);
map.put(6, 4);
map.put(7, 8);
Set<Entry<Integer, Integer>> entrySet = map.entrySet();
List<Entry<Integer, Integer>> List = new ArrayList<>(entrySet);
Collections.sort(List, new Comparator<Entry<Integer, Integer>>() {
@Override
public int compare(Entry<Integer, Integer> o1, Entry<Integer, Integer> o2) {
// TODO Auto-generated method stub
return o2.getValue()-o1.getValue();
}
});
for (Entry<Integer, Integer> e: List) {
System.out.printf(e.getKey()+"="+e.getValue()+" ");
}
}
}
7=8 2=7 6=4 4=3 1=2 3=1