欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

重读JDK1.8

程序员文章站 2022-05-17 11:33:23
...

 

集合排序:Collections.sort

 

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

public class Test {
    public static void main(String[] args) {
        ArrayList<UserInfo> list = new ArrayList<UserInfo>();
        UserInfo info1 = new UserInfo("A","男",14);
        UserInfo info2 = new UserInfo("B","女",13);
        UserInfo info3 = new UserInfo("C","男",12);
        UserInfo info4 = new UserInfo("F","女",16);
        UserInfo info5 = new UserInfo("D","女",19);
        UserInfo info6 = new UserInfo("E","男",23);
        list.add(info1);list.add(info2);list.add(info3);list.add(info4);list.add(info5);list.add(info6);
        System.out.println("===============排序前===================");
        list.stream().forEach(l->{
            System.out.println(l.toString());
        });
        Collections.sort(list, new Comparator<UserInfo>() {
            @Override
            public int compare(UserInfo o1, UserInfo o2) {
                if(o1.age-o2.age>0){
                    return -1;
                }
                if(o1.age-o2.age<0){
                    return 1;
                }
                return 0;

            }
        });
        System.out.println("===============排序后===================");
        list.stream().forEach(l->{
            System.out.println(l.toString());
        });
    }
}
  class UserInfo{
    String username;
    String sex;
    Integer age;

      public String getUsername() {
          return username;
      }

      public void setUsername(String username) {
          this.username = username;
      }

      public String getSex() {
          return sex;
      }

      public void setSex(String sex) {
          this.sex = sex;
      }

      public Integer getAge() {
          return age;
      }

      public void setAge(Integer age) {
          this.age = age;
      }

      public UserInfo(String username, String sex, Integer age) {
          this.username = username;
          this.sex = sex;
          this.age = age;
      }
      public UserInfo() {
      }

      @Override
      public String toString() {
          return "UserInfo{" +
                  "username='" + username + '\'' +
                  ", sex='" + sex + '\'' +
                  ", age=" + age +
                  '}';
      }

  }

===============排序前===================
UserInfo{username='A', sex='男', age=14}
UserInfo{username='B', sex='女', age=13}
UserInfo{username='C', sex='男', age=12}
UserInfo{username='F', sex='女', age=16}
UserInfo{username='D', sex='女', age=19}
UserInfo{username='E', sex='男', age=23}
===============排序后===================
UserInfo{username='E', sex='男', age=23}
UserInfo{username='D', sex='女', age=19}
UserInfo{username='F', sex='女', age=16}
UserInfo{username='A', sex='男', age=14}
UserInfo{username='B', sex='女', age=13}
UserInfo{username='C', sex='男', age=12}