Custom sorting of Lists includes methods implemented using lambda expressions

1. First implement the interface of Comparator and rewrite the compare method to return the value according to the comparison size:

For example: (Integer o1 - Integer o2);

return 1 means o1>o2;

return -1 means o1<o2;

return 0 means o1 = o2;

Therefore, the elements in the TreeSet can be arranged in ascending or descending order according to this return value. The following demonstrates how to implement the interface and rewrite it to customize the sorting:

@Override
			public int compare(Object o1, Object o2) {
				
				 if(o1 instanceof People & o2 instanceof People){
				People p1 = (People) o1;
				People p2 = (People) o2;
				if(p1.getAge()>p2.getAge()){
					return -1;
				}else if(p1.getAge()<p2.getAge()){
					return 1;
				}
				 }
				
				return 0;
			}
			
			
		};

 

	List<Integer> li = new ArrayList<Integer>();
		
		li.add(7);
		li.add(0);
		li.add(3);
		
		li.sort(new Comparator<Integer>() {

			@Override
			public int compare(Integer o1, Integer o2) {

				Integer i1 = o1;
				Integer i2 = o2;
				if(i1>i2) {
					return 1;
					
				}else if(i1<i2) {
					return -1;
				}
				
				return 0;
			}
			
			
		});

   The following is a way to customize the sorting using lambda expressions:

 

	li.sort((o1,o2)->(o2 -  o1   )
		
		);
	
	
	System.out.println(li);

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325077586&siteId=291194637