1. 自定义Comparator排序

  1. public static void main(String[] args) {
  2. List<FormDataDetail> list = new ArrayList<>();
  3. FormDataDetail detail1 = new FormDataDetail();
  4. detail1.setContent("1");
  5. detail1.setDataIndex(1l);
  6. FormDataDetail detail2 = new FormDataDetail();
  7. detail2.setContent("2");
  8. detail2.setDataIndex(2l);
  9. FormDataDetail detail3 = new FormDataDetail();
  10. detail3.setContent("3");
  11. detail3.setDataIndex(3l);
  12. FormDataDetail detail4 = new FormDataDetail();
  13. detail4.setContent("4");
  14. detail4.setDataIndex(4l);
  15. list.add(detail1);
  16. list.add(detail3);
  17. list.add(detail2);
  18. list.add(detail4);
  19. FormDataDetail [] a = list.toArray(new FormDataDetail[list.size()]);
  20. for (FormDataDetail formDataDetail : list) {
  21. System.out.println(formDataDetail.getContent());
  22. }
  23. System.out.println("=======================");
  24. Arrays.sort(a, new Comparator<FormDataDetail>() {
  25. @Override
  26. public int compare(FormDataDetail o1, FormDataDetail o2) {
  27. // System.out.println("o1 =>" + o1.getDataIndex() + " o2 =>" + o2.getDataIndex() + " ");
  28. // System.out.println(o1.getDataIndex() > o2.getDataIndex());
  29. return o1.getDataIndex() > o2.getDataIndex() ? 0 : -1;
  30. }
  31. });
  32. for (FormDataDetail formDataDetail : a) {
  33. System.out.println(formDataDetail.getContent());
  34. }
  35. }

image.png