W3Schools Learner's Blog

w3Schools programming knowledge summary website

div

4/25/2018

List sort(Comparator c):How to sort List

List sort(Comparator<? super E> c) 

public void sort(Comparator<? super E> c)

Description copied from interface: List

Sorts this list according to the order induced by the specified Comparator.
All elements in this list must be mutually comparable using the specified comparator (that is, c.compare(e1, e2) must not throw a ClassCastException for any elements e1 and e2 in the list).

If the specified comparator is null then all elements in this list must implement the Comparable interface and the elements' natural ordering should be used.

This list must be modifiable, but need not be resizable.
Specified by:sort in interface List<E>Parameters:c - the Comparator used to compare list elements. A null value indicates that the elements' natural ordering should be used

For Example:
  1. import java.util.ArrayList;
  2. import java.util.Comparator;
  3. import java.util.List;

  4. public class MapDemo {
  5. public static void main(String[] args) {
  6.   //sort Object type
  7. List<Student> list = new ArrayList<Student>();
  8. list.add(new Student("Jack", 30));
  9. list.add(new Student("Tom", 35));
  10. list.add(new Student("ROSE", 20));
  11. list.sort(new Comparator<Student>() {
  12. @Override
  13. public int compare(Student stu1, Student stu2) {
  14. //according student age ASC
  15. return stu1.getAge().compareTo(stu2.getAge());
  16. }
  17. });
  18. //print student name and age
  19. for (Student s : list) {
  20. System.out.println(s.getName()+"==="+s.getAge());
  21. }
  22. //sort basic type 
  23. List<Integer> list2 = new ArrayList<Integer>();
  24. list2.add(20);
  25. list2.add(18);
  26. list2.add(30);
  27. list2.sort(new Comparator<Integer>() {
  28. @Override
  29. public int compare(Integer num1, Integer num2) {
  30. return num1.compareTo(num2);
  31. }
  32. });
  33. //print number
  34. for (Integer num : list2) {
  35. System.out.println(num);
  36. }
  37. }
  38. }

2 comments:

  1. To be frank, it's turkish to me, but anyway I find it very inspirational, I would say! Obviously, I know things on Java, but machine learning has been the very thing that makes me mazed since I've got to know about it about a year ago. Actually, this is the very reason I've decided to start my way with programing! Now I'm standing with this resource that has a great amount of tutorials on common aspects of java core https://explainjava.com/install-update-remove-java/ provided here. Anyway, I'll check your github and maybe after some swotting things would become more clear to me

    ReplyDelete

Note: only a member of this blog may post a comment.