Java8 集合去重和排序

java 8 去重和排序

 

排序的方法

 List<Integer> lists = Arrays.asList(1,1,2,3);


  // 升序
lists.sort(Comparator.comparing(Integer::intValue));

  // 降序
lists.sort(Comparator.comparing(Integer::intValue).reversed());


或者

// 升序
  lists.stream().sorted().collect(Collectors.toList());
   
// 降序    
lists.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());

 

 

 

 

import java.util.*;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        List<Integer> lists = Arrays.asList(1,1,2,3);
        List<Integer> collect = distinctFiled(lists);
        System.out.println(collect);
        System.out.println(sortFiled(lists));
        List<User> users = Arrays.asList(
          new User(1,"小王","男"),
          new User(2,"小李","男"),
          new User(3,"小张","女"),
          new User(2,"小三","男"));
        List<User> userList = distinctObjectFiled(users);
        System.out.println(userList);
        System.out.println(sortObjectFiled(users));
    }

    /**
     * 根据用户的性别去重
     * @param users
     * @return
     */
    private static List<User> distinctObjectFiled(List<User> users) {

        return users.stream().collect(
                Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(User::getSex))), ArrayList::new)
        );


    }
    /**
     * 根据用户id排序
     * @param users
     * @return
     */
    private static List<User> sortObjectFiled(List<User> users) {
        users.sort(Comparator.comparing(User::getId));
        return users;


    }

    /**
     * 去除重复的属性
     * @param lists
     * @return
     */
    private static List<Integer> distinctFiled(List<Integer> lists) {
        return lists.stream().distinct().collect(Collectors.toList());
    }
      /**
     * 排序
     * @param lists
     * @return
     */
    private static List<Integer> sortFiled(List<Integer> lists) {
         lists.sort(Comparator.comparing(Integer::intValue));
         return lists;
    }





}

model

public class User {

    private Integer id;

    private String name;

    private String sex;

    public User() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public User(Integer id, String name, String sex) {
        this.id = id;
        this.name = name;
        this.sex = sex;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", sex='" + sex + '\'' +
                '}';
    }

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

 

posted @ 2019-11-30 21:16  1994的地铁  阅读(4058)  评论(0编辑  收藏  举报