Talking about java custom sorting (multidimensional sorting) (array, list, set, map)

Foreword:

Speaking of sorting, I can't help but think of the Arrays.sort() method, but it has only one order, that is, ascending order. However, the requirements in the question we are doing may not be in ascending order, or the elements are not necessarily one-dimensional, so what should we do?

Array:

              If the elements are one-dimensional, just use Arrays.sort(), but what if you want to reverse the order? emm. . . Bingo, the output will be finished backwards.

              If the element is two-dimensional and above, you must define your own rules. There are two methods: 1. Customize the container sorting rules, (override cmp and inherit the comparator interface) 2. Customize the sorting rules of the class, so The elements themselves are comparative. (Own class inherits the comparable interface)

code show as below:



import java.util.Arrays;
import java.util.Comparator;

public class Array {

	static class Coordinate{
		int x;
		int y;
		public Coordinate(int x,int y){
			this.x=x;
			this.y=y;
		}
	} 
	
	static class MyComparator1 implements Comparator<Object>
    //让容器自身具备比较性,自定义比较器。
	{	
		public int compare(Object o1, Object o2) {
			Coordinate a=(Coordinate) o1;
			Coordinate b=(Coordinate) o2;
			if(a.x==b.x)
				return a.y-b.y;//小于优先级高一点
			else
			{
				//System.out.println(a.x+" "+b.x+" "+(a.x-b.x));
				return a.x-b.x;
                //返回true a的优先级低 b排在其前面  反之,a的优先级高,排在前面
			}
		}
		
	}
	static class MyComparator2 implements Comparator<Coordinate>
    //让容器自身具备比较性,自定义比较器。
	{	
		public int compare(Coordinate o1, Coordinate o2) {
			Coordinate a=o1;
			Coordinate b=o2;
			if(a.x==b.x)
				return b.y-a.y;//大于优先级高
			else
				return b.x-a.x;
		}
		
	}
	
	static void init(Coordinate a[])
	{
		for(int i=0;i<a.length-1;i++)
			a[i]=new Coordinate(i,i+1);
		a[a.length-1]=new Coordinate(0,-1);
	}
	static void output2(Coordinate a[])
	{
		for(int i=0;i<a.length;i++)
			System.out.print("("+a[i].x+" "+a[i].y+")"+" ");
		System.out.println();
	}
	

	static class Coordinate3 implements Comparable<Coordinate3>//让元素自身具备比较性
	{
		int x;
		int y;
		public Coordinate3(int x,int y){
			this.x=x;
			this.y=y;
		}
		@Override
		public int compareTo(Coordinate3 o) {
			
			if(this.x==o.x)
				return this.y-o.y;//升序
			else
				return this.x-o.x;
		}
	} 
	
	static void init3(Coordinate3 a[])
	{
		for(int i=0;i<a.length-1;i++)
			a[i]=new Coordinate3(i,i+1);
		a[a.length-1]=new Coordinate3(0,-1);
	}
	static void output3(Coordinate3 a[])
	{
		for(int i=0;i<a.length;i++)
			System.out.print("("+a[i].x+" "+a[i].y+")"+" ");
		System.out.println();
	}
	

	//元素一维
	static void output(int a[],boolean flag)
	{
		if(flag)//升序
			for(int i=0;i<a.length;i++)
				System.out.print(a[i]+" ");
		else//降序
			for(int i=a.length-1;i>=0;i--)
				System.out.print(a[i]+" ");
		System.out.println();
	}
	
	
	
	
	public static void main(String[] args) {
		int	a[]={1,4,3,2,5};
		Arrays.sort(a);
		System.out.println("元素一维正序排列:");
		output(a,true);//true 正序
		System.out.println("元素一维倒序排列:");//额,倒序输出就OK了
		output(a,false);
		
		System.out.println("元素多维Comparator方法");
		Coordinate a2[]=new Coordinate[5];
		init(a2);
		
		System.out.println("原始:");
		output2(a2);
		
		Arrays.sort(a2,new MyComparator1());//升序
		System.out.println("排序1升序后");
		output2(a2);
		
		Arrays.sort(a2,new MyComparator2());//降序
		System.out.println("排序2降序后");
		output2(a2);
		
		System.out.println("元素多维Comparable方法");
		Coordinate3 a3[]=new Coordinate3[5];//使类具有排序功能,继承
		init3(a3);
		
		System.out.println("原始:");
		output3(a3);
		
		
		Arrays.sort(a3);
		System.out.println("排序后");
		output3(a3);

	}

}

Output:

One-dimensional positive order of elements:
1 2 3 4 5 
One-dimensional reverse order of elements:
5 4 3 2 1 
Element multi-dimensional Comparator method
Original:
(0 1) (1 2) (2 3) (3 4) (0 -1) 
Sort 1 after ascending order
(0 -1) (0 1) (1 2) (2 3) (3 4) 
Sort 2 after descending order
(3 4) (2 3) (1 2) (0 1) (0 -1) 
Element Multidimensional Comparable Method
Original:
(0 1) (1 2) (2 3) (3 4) (0 -1) 
After sorting
(0 -1) (0 1) (1 2) (2 3) (3 4) 

               

Linked list:

               Linked list, I use ArrayList most often, LinkedList has also been used, but most of them are used when using queue or stack, emm, the following is an example of ArrayList for analysis:

               In fact, for one-dimensional, you need to call Collections.sort();

               Multi-dimensional words, or the above two methods: 1. Customize the container sorting rules, (override cmp to inherit the comparator interface) 2. Customize the sorting rules of the class to make the elements themselves more comparable. (Own class inherits the comparable interface)

code show as below:



import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class List {

	//元素一维
	static void output(ArrayList<Integer> list)
	{
		for(int i=0;i<list.size();i++)
			System.out.print(list.get(i)+" ");
		System.out.println();
	}
	//多维
	static class Coordinate2{
		int x;
		int y;
		public Coordinate2(int x,int y){
			this.x=x;
			this.y=y;
		}
	} 
	
	static class MyComparator implements Comparator<Coordinate2>
    //让容器自身具备比较性,自定义比较器。
	{	
		public int compare(Coordinate2 o1, Coordinate2 o2) {
			
			if(o1.x==o2.x)
				return o1.y-o2.y;//小于优先级高一点
			else
				return o1.x-o2.x;
        //返回true a的优先级低 b排在其前面  反之,a的优先级高,排在前面
		}
		
	}
	
	
	static void init2(ArrayList<Coordinate2> list)
	{
		for(int i=0;i<4;i++)
			list.add(new Coordinate2(i,i+1));
		list.add(new Coordinate2(0,-1));
		
	}
	static void output2(ArrayList<Coordinate2> list)
	{
		for(int i=0;i<list.size();i++)
			System.out.print("("+list.get(i).x+" "+list.get(i).y+")"+" ");
		System.out.println();
	}
	

	static class Coordinate3 implements Comparable<Coordinate3>//让元素自身具备比较性
	{
		int x;
		int y;
		public Coordinate3(int x,int y){
			this.x=x;
			this.y=y;
		}
		@Override
		public int compareTo(Coordinate3 o) {
			
			if(this.x==o.x)
				return this.y-o.y;//升序
			else
				return this.x-o.x;
		}
	} 
	
	static void init3(ArrayList<Coordinate3> list)
	{
		for(int i=0;i<4;i++)
			list.add(new Coordinate3(i,i+1));
		list.add(new Coordinate3(0,-1));
		
	}
	static void output3(ArrayList<Coordinate3> list)
	{
		for(int i=0;i<list.size();i++)
			System.out.print("("+list.get(i).x+" "+list.get(i).y+")"+" ");
		System.out.println();
	}
	
	
	public static void main(String[] args) {
		ArrayList<Integer> list=new ArrayList<Integer>();
		list.add(1);
		list.add(3);
		list.add(2);
		list.add(5);
		list.add(4);
		
		System.out.println("原始:");
		output(list);
		
		Collections.sort(list);
		System.out.println("元素一维正序排列:");
		output(list);//true 正序
		
		
		System.out.println("元素多维Comparator方法");
		ArrayList<Coordinate2> list2=new ArrayList<Coordinate2>();
		init2(list2);
		
		System.out.println("原始:");
		output2(list2);
		
		Collections.sort(list2,new MyComparator());//升序
		System.out.println("排序升序后");
		output2(list2);
		
		System.out.println("元素多维Comparable方法");
		ArrayList<Coordinate3> list3=new ArrayList<Coordinate3>();
        //使类具有排序功能
		init3(list3);
		
		System.out.println("原始:");
		output3(list3);
		
		Collections.sort(list3);
		System.out.println("排序后");
		output3(list3);

	}
}

Output:

Original:
1 3 2 5 4- 
element one-dimensional positive order arrangement:
1 2 3 4 5- 
element multi-dimensional Comparator method
Original:
(0 1) (1 2) (2 3) (3 4) (0 -1) After 
sorting in ascending order
( 0 -1) (0 1) (1 2) (2 3) (3 4) 
Element Multidimensional Comparable Method
Original:
(0 1) (1 2) (2 3) (3 4) (0 -1) 
After sorting
( 0 -1) (0 1) (1 2) (2 3) (3 4) 

set:

            set: a collection of no repeated elements, hashset: the property is the same as set, but a bit faster than set, treeSet: the elements are unique and ordered.

            One-dimensional direct TreeSet. (Sorry, TreeSet can do whatever it wants~)

            The two methods are also multi-dimensional. Inheriting comparable makes the class self-ordering, and inheriting comparator to write your own cmp. It should be emphasized that when the above two situations exist at the same time, the latter plays a decisive role.

code show as below:



import java.util.Comparator;
import java.util.TreeSet;
import java.util.Iterator;

public class Set {

	//元素一维
	static void output(TreeSet<String> set)
	{
		Iterator<String> iterator=set.iterator();
		while(iterator.hasNext())
		{
			String next=iterator.next();
			System.out.print(next+" ");
		}
		System.out.println();
	}
	//多维
	static class Coordinate2{
		int x;
		int y;
		public Coordinate2(int x,int y){
			this.x=x;
			this.y=y;
		}
	} 
	
	static class MyComparator implements Comparator<Coordinate2>//让容器自身具备比较性,自定义比较器。
	{	
		public int compare(Coordinate2 o1, Coordinate2 o2) {
			
			if(o1.x==o2.x)
				return o2.y-o1.y;//大于优先级高一点
			else
				return o2.x-o1.x;//相当于重载小于号,o2.x<o1.x
		}
		
	}
	
	
	static void init2(TreeSet<Coordinate2> set)
	{
		set.add(new Coordinate2(1,0));
		set.add(new Coordinate2(2,0));
		set.add(new Coordinate2(3,0));
		set.add(new Coordinate2(1,-1));
		set.add(new Coordinate2(2,-1));
		set.add(new Coordinate2(3,-1));
		set.add(new Coordinate2(1,-1));
		set.add(new Coordinate2(2,-1));
		set.add(new Coordinate2(3,-1));
	}
	static void output2(TreeSet<Coordinate2> set)
	{
		Iterator<Coordinate2> iterator=set.iterator();
		while(iterator.hasNext())
		{
			Coordinate2 C= iterator.next();
			System.out.print("("+C.x+" "+C.y+")"+" ");
		}
		System.out.println();
	}
	

	static class Coordinate3 implements Comparable<Coordinate3>//让元素自身具备比较性
	{
		int x;
		int y;
		public Coordinate3(int x,int y){
			this.x=x;
			this.y=y;
		}
		@Override
		public int compareTo(Coordinate3 o) {
			
			if(this.x==o.x)
				return o.y-this.y;//降序
			else
				return o.x-this.x;
		}
	} 
	
	static void init3(TreeSet<Coordinate3> set)
	{
		set.add(new Coordinate3(1,0));
		set.add(new Coordinate3(2,0));
		set.add(new Coordinate3(3,0));
		set.add(new Coordinate3(1,-1));
		set.add(new Coordinate3(2,-1));
		set.add(new Coordinate3(3,-1));
		set.add(new Coordinate3(1,0));//元素唯一
		set.add(new Coordinate3(2,0));
		set.add(new Coordinate3(3,0));
	}
	static void output3(TreeSet<Coordinate3> set)
	{
		Iterator<Coordinate3> iterator=set.iterator();//迭代器
		while(iterator.hasNext())
		{
			Coordinate3 C= iterator.next();
			System.out.print("("+C.x+" "+C.y+")"+" ");
		}
		System.out.println();
	}
	
	
	public static void main(String[] args) {
		TreeSet<String> set=new TreeSet<String>();
		set.add("a");
		set.add("e");
		set.add("c");
		set.add("c");//元素唯一
	
		System.out.println("元素一维正序排列:");
		output(set);//true 正序
		
		
		System.out.println("元素多维Comparator方法//降序");
		TreeSet<Coordinate2> set2=new TreeSet<Coordinate2>(new MyComparator());
		init2(set2);
		output2(set2);
		
		System.out.println("元素多维Comparable方法//降序");
		TreeSet<Coordinate3> set3=new TreeSet<Coordinate3>();//使类具有排序功能,继承
		init3(set3);
		output3(set3);

	}
}

Output result:

Elements in one-dimensional positive order:
ace 
element multi-dimensional Comparator method // descending order
(3 0) (3 -1) (2 0) (2 -1) (1 0) (1 -1) 
element multi-dimensional Comparable method // descending order
( 3 0) (3 -1) (2 0) (2 -1) (1 0) (1 -1) 

map:

The Chinese meaning of map is mapping, which is also its essence. Each element of her is composed of (key, value) key-value pairs.

Its characteristic is that the key value is unique, one to one correspondence.

Common map in java:

HashMap (unordered)

The most commonly used Map, it stores data according to the HashCode value of the key, and its value can be obtained directly according to the key, which has a very fast access speed. HashMap only allows at most one record to have a key of Null (multiple records will be overwritten); allow multiple records to have a value of Null. Asynchronous.

TreeMap (ordered)

The records it saves can be sorted according to the key. The default is to sort in ascending order. You can also specify the sorting comparator. When iterator is used to traverse the TreeMap, the records obtained are sorted. TreeMap does not allow the value of key to be null. Asynchronous. 

Hashtable

Similar to HashMap, the difference is: the values ​​of key and value are not allowed to be null; it supports thread synchronization, that is, only one thread can write Hashtable at any time, which also causes Hashtale to be slow when writing. 

LinkedHashMap

The insertion order of records is saved. When iterator is used to traverse LinkedHashMap, the first record must be inserted first. It will be slower than HashMap when traversing. Both key and value are allowed to be empty and asynchronous. 

Common API: Note the difference between EntrySet and KeySet

clear() Remove all maps from the map
remove(Object key) Delete keys and associated values ​​from the Map
put(Object key, Object value) Associate the specified value with the specified key
putAll(Map t) Copy all maps in the specified Map to this map
entrySet() Returns the Set view of the map contained in the Map. Each element in the Set is a Map.Entry object, you can use the getKey() and getValue() methods (and a setValue() method) to access the latter’s key elements and value elements
keySet() Returns the Set view of the keys contained in the Map. Deleting elements in Set will also delete the corresponding mapping (key and value) in Map
values() Returns a Collection view of the values ​​contained in the map. Deleting an element in the Collection will also delete the corresponding mapping (key and value) in the Map
get(Object key) Returns the value associated with the specified key
containsKey(Object key) Returns true if the Map contains a map for the specified key
containsValue(Object value) Returns true if this Map maps one or more keys to the specified value
isEmpty() If the Map does not contain a key-value mapping, return true
size() Returns the number of key-value mappings in the Map

Generally we use TreeMap a little more when sorting, so let's take TreeMap as an example to illustrate

code show as below:



import java.util.Iterator;
import java.util.TreeMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class Map解析 {

	static void init(TreeMap<String,Integer> map)
	{
		map.put("z", 6);
		map.put("y", 6);
		map.put("y", 7);
		map.put("a", 9);
		map.put("b", 100);
		map.put("c", 100);
		
	}

	static void output(TreeMap<String,Integer> map)
	{
		Iterator<String> iterator= map.keySet().iterator();
		while(iterator.hasNext())//不能在其遍历时改变其值,不然会报错
		{
			String next=iterator.next();
			System.out.print("("+next+","+map.get(next)+")"+" ");
		}
		System.out.println();		
	}
	
	static void output2(List<Map.Entry<String, Integer>> list)
	{
		Iterator<Entry<String, Integer>> iterator= list.iterator();//遍历速度最快
		while(iterator.hasNext())//不能在其遍历时改变其值,不然会报错
		{
			Entry<String, Integer> next=iterator.next();
			System.out.print("("+next.getKey()+","+next.getValue()+")"+" ");
		}
		System.out.println();		
	}
	
	public static void main(String[] args) {
		TreeMap<String,Integer> map=new TreeMap<String, Integer>();
		init(map);
		System.out.println("原始升序");
		output(map);
		
		System.out.println("继承comparator,写cmp比较器比较");
        System.out.println("方法一,转化为list,然后集合排序");
		System.out.println("排序规则:value值越大,优先级越高,越排在前面,value相同,key值越低,越排在前面");
		List<Map.Entry<String, Integer>> list=new ArrayList<Map.Entry<String, Integer>>(map.entrySet());
		//通过ArrayList将Map.Entry<String, Integer>为list,
		//集合排序
		Collections.sort(list,new Comparator<Map.Entry<String, Integer>>(){
		//构造cmp Comparator<object>
			public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2)             {
				if(o1.getValue()==o2.getValue())
					return o1.getKey().compareTo(o2.getKey());//相当于小于运算符
				else
					return o2.getValue()-o1.getValue();
				
			}
			
		});
		output2(list);
		
		System.out.println("方法二,不用转化list,直接应用cmp,仅适用于TreeMap,(类似于TreeSet)逆序输出");
		TreeMap<String,Integer> map2=new TreeMap<String, Integer>(new Comparator<String>(){
			public int compare(String o1, String o2) {
				return o2.compareTo(o1);
			}
			
		});
		init(map2);
		output(map2);
		
	}

}

Output result:

Original ascending order
(a,9) (b,100) (c,100) (y,7) (z,6) 
Inherit the comparator, write cmp comparator comparison
sorting rules: the larger the value, the higher the priority, the more row In the front, the value is the same, the lower the key value, the more it ranks in the front
(b,100) (c,100) (a,9) (y,7) (z,6) 
Method two, do not need to convert the list, directly apply cmp , Only applicable to TreeMap, (similar to TreeSet) output in reverse order
(z,6) (y,7) (c,100) (b,100) (a,9) 
 

summary:

。。。

Here, finally finished! ! !

The day after tomorrow will be the Blue Bridge Cup, I hope it can be used.

Guess you like

Origin blog.csdn.net/Look_star/article/details/88735135