List 常用用法

准备

user.sql

CREATE TABLE `user` (
  `id` int(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `username` varchar(100) DEFAULT NULL COMMENT '用户名',
  `password` varchar(100) DEFAULT NULL COMMENT '密码',
  `nickname` varchar(100) DEFAULT NULL COMMENT '昵称',
  `age` int(10) DEFAULT NULL COMMENT '年龄',
  `gender` varchar(10) DEFAULT NULL COMMENT '性别',
  `birthday` date DEFAULT NULL COMMENT '生日',
  `phone` varchar(20) DEFAULT NULL COMMENT '电话',
  `email` varchar(50) DEFAULT NULL COMMENT '邮箱',
  `address` varchar(200) DEFAULT NULL COMMENT '地址',
  `create_datetime` datetime DEFAULT NULL COMMENT '创建时间',
  `update_datetime` datetime DEFAULT NULL COMMENT '更新时间',
  `delete_status` int(1) DEFAULT NULL COMMENT '删除状态',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='用户';

User.java

package com.xzh.demo.domin;

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.springframework.format.annotation.DateTimeFormat;

import java.text.SimpleDateFormat;
import java.util.Date;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {

    // 主键
    private Integer id;
    // 用户名
    private String username;
    // 密码
    private String password;
    // 昵称
    private String nickname;
    // 年龄
    private Integer age;
    // 性别
    private String gender;
    // 生日
    @JsonFormat(timezone="GMT+8", pattern="yyyy-MM-dd")
    @DateTimeFormat(pattern="yyyy-MM-dd")
    private Date birthday;
    // 电话
    private String phone;
    // 邮箱
    private String email;
    // 地址
    private String address;
    // 创建时间
    @JsonFormat(timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date createDatetime;
    // 更新时间
    @JsonFormat(timezone="GMT+8", pattern="yyyy-MM-dd HH:mm:ss")
    @DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
    private Date updateDatetime;
    // 删除状态
    private Integer deleteStatus;

    public User(String username, String password, String nickname, Integer age, String gender, Date birthday, String phone, String email, String address, Date createDatetime, Date updateDatetime, Integer deleteStatus) {
        this.username = username;
        this.password = password;
        this.nickname = nickname;
        this.age = age;
        this.gender = gender;
        this.birthday = birthday;
        this.phone = phone;
        this.email = email;
        this.address = address;
        this.createDatetime = createDatetime;
        this.updateDatetime = updateDatetime;
        this.deleteStatus = deleteStatus;
    }

    @Override
    public String toString() {
        SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String birthdayStr = birthday != null ? sdf1.format(birthday) : "'null'";
        String createDatetimeStr = createDatetime != null ? sdf2.format(createDatetime) : "'null'";
        String updateDatetimeStr = updateDatetime != null ? sdf2.format(updateDatetime) : "'null'";
        return "User{" +
                "id=" + id +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", nickname='" + nickname + '\'' +
                ", age=" + age +
                ", gender='" + gender + '\'' +
                ", birthday=" + birthdayStr +
                ", phone='" + phone + '\'' +
                ", email='" + email + '\'' +
                ", address='" + address + '\'' +
                ", createDatetime=" + createDatetimeStr +
                ", updateDatetime=" + updateDatetimeStr +
                ", deleteStatus=" + deleteStatus +
                '}';
    }
}

数据准备

public class StudyList {

    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    private List<User> userList = new ArrayList<User>() {{
        try {
            add(new User(1, "zs", "3", "张三", 14, "男",
                    sdf1.parse("2020-07-06"), "13067201234", "133266@qq.com", "福州",
                    sdf2.parse("2020-07-06 00:51:44"), sdf2.parse("2020-07-06 00:49:04"), 0));
            add(new User(2, "ls", "123", "李四", 12, "男",
                    sdf1.parse("2020-08-29"), "13067201234", "133266@qq.com", "四川",
                    sdf2.parse("2020-07-07 09:16:18"), sdf2.parse("2020-07-06 00:49:04"), 0));
            add(new User(3, "ww", "1", "王五", 15, "男",
                    sdf1.parse("2020-07-06"), "13067201234", "133266@qq.com", "福州",
                    sdf2.parse("2020-07-06 00:51:44"), sdf2.parse("2020-07-06 00:49:04"), 0));
            add(new User(4, "super", "3", "超管", 13, "男",
                    sdf1.parse("2020-07-06"), "13067201234", "133266@qq.com", "福州",
                    sdf2.parse("2020-07-06 00:51:44"), sdf2.parse("2020-07-06 00:49:04"), 0));
            add(new User(5, "zs", "3", "管理员1", 14, "男",
                    sdf1.parse("2020-07-06"), "13067201234", "133266@qq.com", "福州",
                    sdf2.parse("2020-07-06 00:51:44"), sdf2.parse("2020-07-06 00:49:04"), 0));
            add(new User(6, "root;", "2", "管理员2", 16, "男",
                    sdf1.parse("2020-07-06"), "13067201234", "133266@qq.com", "福州",
                    sdf2.parse("2020-07-06 00:51:44"), sdf2.parse("2020-07-06 00:49:04"), 0));
            add(new User(7, "root", ";2", "管理员3", 14, "男",
                    sdf1.parse("2020-07-06"), "13067201234", "133266@qq.com", "福州",
                    sdf2.parse("2020-07-06 00:51:44"), sdf2.parse("2020-07-06 00:49:04"), 0));
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }};
}

List 常用用法

添加

// 添加
public void add() {
    User user = new User();
    user.setId(10);
    user.setUsername("test");
    userList.add(user);
}

插入

// 插入
public void insert() {
    User user = new User();
    user.setId(10);
    user.setUsername("test");
    userList.add(2, user);
}

删除

// 删除(按对对象)
public void delete1() {
    // boolean remove(Object o);
    userList.remove(userList.get(0));
}

// 删除(按位序)
public void delete2() {
    // E remove(int index)
    User remove = userList.remove(2);
}

// 删除(按条件)
public void delete3() {
    // boolean removeIf(Predicate<? super E> filter)
    userList.removeIf(obj -> obj.getPassword().equals("1"));
}

替换

// 替换
public void reset() {
    User user = userList.get(1);
    user.setUsername("替换");
    userList.set(1, user);
}

获取

// 获取
public void get() {
    User user = userList.get(1);
    System.out.println(user);
}

截取

// 截取
public void sub() {
    // List<E> subList(int fromIndex, int toIndex); 范围 [fromIndex, toIndex)
    List<User> list = userList.subList(3, 4);
}

转数组

// 转数组
public void toArray() {
    List<String> list = Arrays.asList("a", "b", "c");
    String[] array = list.toArray(new String[list.size()]);
    for (String s : array) {
        System.out.print(s + " ");
    }
}

判空

判断元素个数是否为0,不能判断是否为空指针

public void isEmpty() {
    List list = new ArrayList();
    System.out.println(list.isEmpty());
}

判断是否为空指针且元素个数是否为0

public void isBlank() {
    boolean bool = userList == null || userList.isEmpty();
    System.out.println(bool);

}

判包含

单字段

// 判包含(单字段)
public void isContains() {
    long count = userList.stream().map(User::getUsername).filter(e -> "ls".equals(e)).count();
    System.out.println(count > 0);
}

多字段

// 判包含(多字段)
public void isContains2() {
    long count = userList.stream().map(e -> e.getUsername() + ',' + e.getPassword()).filter(e -> "zs,,1".equals(e)).count();
    System.out.println(count > 0);
}

// 判包含(多字段)
public void isContains3() {
    User user = new User();
    user.setUsername("zs,");
    user.setPassword("1");
    boolean b = userIndexOf(user) >= 0;
    System.out.println(b);
}

public int userIndexOf(Object o) {
    if (o == null) {
        for (int i = 0; i < userList.size(); i++)
            if (userList.get(i)==null)
                return i;
    } else {
        for (int i = 0; i < userList.size(); i++)
            if (userEquals(o, userList.get(i)))
                return i;
    }
    return -1;
}

public boolean userEquals(Object u, Object o) {
    if (u == o) return true;
    if (o == null || u.getClass() != o.getClass()) return false;
    User user2 = (User) o;
    User user1 = (User) u;
    return new EqualsBuilder()
            .append(user1.getUsername(), user2.getUsername())
            .append(user1.getPassword(), user2.getPassword())
            .isEquals();
}

判重

单字段

// 判重(单字段)
public void isRepeat() {
    List<String> collect = userList.stream().map(User::getUsername).collect(Collectors.toList());
    Set<?> noRepeatSet = new HashSet<>(collect);
    boolean bool = !(collect.size() == noRepeatSet.size());
    System.out.println(bool);
}

多字段

// 判重(多字段)
public void isRepeat2() {
    List<String> collect = userList.stream().map(e -> e.getUsername() + ',' + e.getPassword()).collect(Collectors.toList());
    Set<?> noRepeatSet = new HashSet<>(collect);
    boolean bool = !(collect.size() == noRepeatSet.size());
    System.out.println(bool);
}

去重

单字段

// 去重1(单字段)
public void distinct1() {
    List<User> list = new ArrayList<>(userList.stream()
            .collect(Collectors.toMap(User::getUsername, Function.identity(), (oldValue, newValue) -> newValue))
            .values());
    listToStr(list);
}

// 去重2(单字段)
public void distinct2() {
    List<User> list = new ArrayList<>(userList.stream()
            .collect(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(User::getUsername)))));
    listToStr(list);
}

多字段

// 去重1(多字段)
public void distinct1_2() {
    List<User> list = new ArrayList<>(userList.stream()
            .collect(Collectors.toMap(e -> e.getUsername() + ',' + e.getPassword(), Function.identity(), (oldValue, newValue) -> newValue))
            .values());
    listToStr(list);
}

// 去重2(多字段)
public void distinct2_2() {
    List<User> list = userList.stream()
            .collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(e -> e.getUsername() + ',' + e.getPassword()))), ArrayList::new));
    listToStr(list);
}

去重

//查重
public static <T> List<T> findRepeat(Collection<T> datas) {
    if (datas instanceof Set) {
        return new ArrayList<>();
    }
    HashSet<T> set = new HashSet<T>();
    List<T> repeatEles = new ArrayList<T>();
    for (T t : datas) {
        if (set.contains(t)) {
            repeatEles.add(t);
        } else {
            set.add(t);
        }
    }
    return repeatEles;
}

排序

单字段

// 排序 单字段
public void sort(){
    List<User> collect = userList.stream().sorted(
            Comparator.comparing(User::getAge)).collect(Collectors.toList());
    listToStr(collect);
}

多字段

// 排序 多字段
public void sort2(){
    List<User> collect = userList.stream().sorted(
            Comparator.comparing(User::getAge).reversed().thenComparing(User::getPassword)).collect(Collectors.toList());
    listToStr(collect);
}

封装工具类

ListUtils.java

package com.xzh.demo.util;

import jdk.internal.org.objectweb.asm.tree.analysis.Value;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.poi.ss.formula.functions.T;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.*;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.stream.Collectors;

public class ListUtils {

    public static final String DESC = "desc";
    public static final String ASC = "asc";

    public static <T> int indexOf(List<T> list, Object obj, BiFunction<? super T, ? super Object, Boolean> equ) {
        if (obj == null) {
            for (int i = 0; i < list.size(); i++)
                if (list.get(i) == null)
                    return i;
        } else {
            for (int i = 0; i < list.size(); i++)
                if (equ.apply(list.get(i), obj))
                    return i;
        }
        return -1;
    }

    public static <T> int indexOf(List<T> list, Object obj, String... fieldNames) {
        if (obj == null) {
            for (int i = 0; i < list.size(); i++)
                if (list.get(i) == null)
                    return i;
        } else {
            for (int i = 0; i < list.size(); i++)
                if (equal(list.get(i), obj, fieldNames))
                    return i;
        }
        return -1;
    }


    /**
     * List 转 String, 用于遍历输出
     */
    public static String toStr(List<?> list) {
       return toStr(list, true);
    }

    /**
     * List 转 String, 用于遍历输出
     */
    public static String toStr(List<?> list, boolean print) {
        StringBuffer str = new StringBuffer();
        for (Object o : list) {
            str.append("\n" + o.toString());
        }
        if (print) {
            System.out.println(str.toString());
        }
        return str.toString();
    }


    /**
     * 判空,只判断元素个数是否为0,不能判断是否为空指针
     */
    public static boolean isEmpty(List<?> list) {
        return list.isEmpty();
    }

    /**
     * 判空
     */
    public static boolean isNullEmpty(List<?> list) {
        return list == null || list.isEmpty();
    }

    /**
     * 判非空
     */
    public static boolean isNotNullEmpty(List<?> list) {
        return !isNullEmpty(list);
    }

    /**
     * 判包含
     *
     * @param list   集合List
     * @param mapper 转换方法
     * @param filter 判包含字符串
     * @return
     */
    public static <T> boolean isContains(List<T> list, Function<? super T, ? super Object> mapper, Object filter) {
        if (filter == null) {
            return false;
        }
        long count = list.stream().map(mapper).filter(e -> filter.equals(e)).count();
        return count > 0;
    }

    /**
     * 判包含
     *
     * @param list   集合List
     * @param equ    equals方法
     * @param filter 判包含字符串
     * @return
     */
    public static <T> boolean isContains(List<T> list, BiFunction<? super T, ? super Object, Boolean> equ, Object filter) {
        if (filter == null) {
            return false;
        }
        return indexOf(list, filter, equ) >= 0;
    }


    /**
     * 判包含
     *
     * @param list       集合List
     * @param filter     判包含字符串
     * @param fieldNames 判断equals相等的字段名
     * @return
     */
    public static <T> boolean isContains(List<T> list, Object filter, String... fieldNames) {
        if (filter == null) {
            return false;
        }
        return indexOf(list, filter, fieldNames) >= 0;
    }


    /**
     * 判重
     *
     * @param list   集合List
     * @param mapper 转换方法
     * @return
     */
    public static <T> boolean isRepeat(List<T> list, Function<? super T, ? super Object> mapper) {
        List<Object> collect = list.stream().map(mapper).collect(Collectors.toList());
        Set<?> noRepeatSet = new HashSet<>(collect);
        return !(collect.size() == noRepeatSet.size());
    }

    /**
     * 判重
     *
     * @param list 集合List
     * @param equ  equals方法
     * @return
     */
    public static <T> boolean isRepeat(List<T> list, BiFunction<? super T, ? super Object, Boolean> equ) {
        List<T> noRepeat = new ArrayList<>();
        for (T t : list) {
            if (isContains(noRepeat, equ, t))
                return true;
            else
                noRepeat.add(t);
        }
        return !(noRepeat.size() == list.size());
    }

    /**
     * 判重
     *
     * @param list       集合List
     * @param fieldNames 判断equals相等的字段名
     * @return
     */
    public static <T> boolean isRepeat(List<T> list, String... fieldNames) {
        List<T> noRepeat = new ArrayList<>();
        for (T t : list) {
            if (isContains(noRepeat, t, fieldNames))
                return true;
            else
                noRepeat.add(t);
        }
        return !(noRepeat.size() == list.size());
    }

    /**
     * 去重
     *
     * @param list    集合List
     * @param mapper  转换方法
     * @param isCover 是否覆盖
     * @return
     */
    public static <T> List<T> removeRepeat(List<T> list, Function<? super T, ? super Object> mapper, boolean isCover) {
        List<T> noRepeat = new ArrayList<T>(list.stream()
                .collect(Collectors.toMap(mapper, Function.identity(), (oldValue, newValue) -> isCover ? newValue : oldValue))
                .values());
        return noRepeat;
    }

    /**
     * 去重
     *
     * @param list    集合List
     * @param equ     equals方法
     * @param isCover 是否覆盖
     * @return
     */
    public static <T> List<T> removeRepeat(List<T> list, BiFunction<? super T, ? super Object, Boolean> equ, boolean isCover) {
        List<T> noRepeat = new ArrayList<>();
        for (T t : list) {
            int i = indexOf(noRepeat, t, equ);
            if (i >= 0) {
                if (isCover)
                    noRepeat.set(i, t);
            } else {
                noRepeat.add(t);
            }
        }
        return noRepeat;
    }

    /**
     * 去重
     *
     * @param list       集合List
     * @param isCover    是否覆盖
     * @param fieldNames 判断equals相等的字段名
     * @return
     */
    public static <T> List<T> removeRepeat(List<T> list, boolean isCover, String... fieldNames) {
        List<T> noRepeat = new ArrayList<>();
        for (T t : list) {
            int i = indexOf(noRepeat, t, fieldNames);
            if (i >= 0) {
                if (isCover)
                    noRepeat.set(i, t);
            } else {
                noRepeat.add(t);
            }
        }
        return noRepeat;
    }

    /**
     * 去重
     *
     * @param list       集合List
     * @param split      分隔符
     * @param fieldNames 判断equals相等的字段名
     * @return
     */
    public static <T> List<T> removeRepeat(List<T> list, String split, String... fieldNames) {
        List<T> noRepeat = new ArrayList<>(list.stream()
                .collect(Collectors.toCollection(() -> new TreeSet<T>(Comparator.comparing(e -> getValuesOfGet(e, split, fieldNames) + "")))));
        return noRepeat;
    }

    /**
     * 查重
     *
     * @param list       集合List
     * @param fieldNames 判断equals相等的字段名
     * @return
     */
    public static <T> List<T> findRepeat(List<T> list, String... fieldNames) {
        List<T> noRrepeat = new ArrayList<>();
        List<T> repeat = new ArrayList<>();
        for (T t : list) {
            if (isContains(noRrepeat, t, fieldNames))
                repeat.add(t);
            else
                noRrepeat.add(t);
        }
        return repeat;
    }

    /**
     * 对list中的元素按升序排列
     *
     * @param list  集合List
     * @param field 用于排序的字段
     * @return
     */
    public static <T> List<T> sorted(List<T> list, final String field) {
        return sorted(list, field, null);
    }

    /**
     * 对list中的元素进行排序
     *
     * @param list  集合List
     * @param field 用于排序的字段
     * @param sort  排序方式: ListUtils.DESC(降序) ListUtils.ASC(升序).
     * @return
     */
    public static <T, U> List<T> sorted(List<T> list, final String field, final String sort) {
        if (isNullEmpty(list)) {
            return list;
        }
        Comparator<T> comparing;
        boolean isDesc = sort != null && sort.toLowerCase().equals(DESC) ? false : true;
        Object value = getValueOfGet(list.get(0), field);
        if (value instanceof Integer) {
            comparing = isDesc ? Comparator.comparing(e -> (Integer) getValueOfGet(e, field)) :
                    Comparator.comparing(e -> (Integer) getValueOfGet(e, field), Comparator.reverseOrder());
        } else if (value instanceof Double) {
            comparing = isDesc ? Comparator.comparing(e -> (Double) getValueOfGet(e, field)) :
                    Comparator.comparing(e -> (Double) getValueOfGet(e, field), Comparator.reverseOrder());
        } else if (value instanceof Long) {
            comparing = isDesc ? Comparator.comparing(e -> (Long) getValueOfGet(e, field)) :
                    Comparator.comparing(e -> (Long) getValueOfGet(e, field), Comparator.reverseOrder());
        } else if (value instanceof Float) {
            comparing = isDesc ? Comparator.comparing(e -> (Float) getValueOfGet(e, field)) :
                    Comparator.comparing(e -> (Float) getValueOfGet(e, field), Comparator.reverseOrder());
        } else if (value instanceof Date) {
            comparing = isDesc ? Comparator.comparing(e -> (Date) getValueOfGet(e, field)) :
                    Comparator.comparing(e -> (Date) getValueOfGet(e, field), Comparator.reverseOrder());
        } else {
            comparing = isDesc ? Comparator.comparing(e -> (String) getValueOfGet(e, field)) :
                    Comparator.comparing(e -> (String) getValueOfGet(e, field), Comparator.reverseOrder());
        }
        return list.stream().sorted(comparing).collect(Collectors.toList());
    }

    /**
     * 对list中的元素按fields和sorts进行排序,
     * fields[i]指定排序字段,sorts[i]指定排序方式.如果sorts[i]为空则默认按升序排列.
     *
     * @param list
     * @param fields
     * @param sorts
     * @return
     */
    public static <T> List<T> sorted(List<T> list, String[] fields, String[] sorts) {
        if (isNullEmpty(list)) {
            return list;
        }
        if (fields != null && fields.length > 0) {
            Comparator<T> comparing = null;
            for (int i = 0; i < fields.length; i++) {
                final String field = fields[i];
                String tmpSort = ASC;
                if (sorts != null && sorts.length > i && sorts[i] != null) {
                    tmpSort = sorts[i];
                }
                final String sort = tmpSort;
                boolean isDesc = sort != null && sort.toLowerCase().equals(DESC) ? false : true;
                Object value = getValueOfGet(list.get(0), field);
                if (i == 0) {
                    if (value instanceof Integer) {
                        comparing = isDesc ? Comparator.comparing(e -> (Integer) getValueOfGet(e, field)) :
                                Comparator.comparing(e -> (Integer) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else if (value instanceof Double) {
                        comparing = isDesc ? Comparator.comparing(e -> (Double) getValueOfGet(e, field)) :
                                Comparator.comparing(e -> (Double) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else if (value instanceof Long) {
                        comparing = isDesc ? Comparator.comparing(e -> (Long) getValueOfGet(e, field)) :
                                Comparator.comparing(e -> (Long) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else if (value instanceof Float) {
                        comparing = isDesc ? Comparator.comparing(e -> (Float) getValueOfGet(e, field)) :
                                Comparator.comparing(e -> (Float) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else if (value instanceof Date) {
                        comparing = isDesc ? Comparator.comparing(e -> (Date) getValueOfGet(e, field)) :
                                Comparator.comparing(e -> (Date) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else {
                        comparing = isDesc ? Comparator.comparing(e -> (String) getValueOfGet(e, field)) :
                                Comparator.comparing(e -> (String) getValueOfGet(e, field), Comparator.reverseOrder());
                    }
                } else {
                    if (value instanceof Integer) {
                        comparing = isDesc ? comparing.thenComparing(e -> (Integer) getValueOfGet(e, field)) :
                                comparing.thenComparing(e -> (Integer) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else if (value instanceof Double) {
                        comparing = isDesc ? comparing.thenComparing(e -> (Double) getValueOfGet(e, field)) :
                                comparing.thenComparing(e -> (Double) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else if (value instanceof Long) {
                        comparing = isDesc ? comparing.thenComparing(e -> (Long) getValueOfGet(e, field)) :
                                comparing.thenComparing(e -> (Long) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else if (value instanceof Float) {
                        comparing = isDesc ? comparing.thenComparing(e -> (Float) getValueOfGet(e, field)) :
                                comparing.thenComparing(e -> (Float) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else if (value instanceof Date) {
                        comparing = isDesc ? comparing.thenComparing(e -> (Date) getValueOfGet(e, field)) :
                                comparing.thenComparing(e -> (Date) getValueOfGet(e, field), Comparator.reverseOrder());
                    } else {
                        comparing = isDesc ? comparing.thenComparing(e -> (String) getValueOfGet(e, field)) :
                                comparing.thenComparing(e -> (String) getValueOfGet(e, field), Comparator.reverseOrder());
                    }
                }
            }
            return list.stream().sorted(comparing).collect(Collectors.toList());
        }
        return list;
    }

    /**
     * 对list中的元素按升序排列.
     *
     * @param list  排序集合
     * @param field 排序字段
     * @return
     */
    public static <T> List<T> sort(List<T> list, final String field) {
        return sort(list, field, null);
    }

    /**
     * 对list中的元素进行排序.
     *
     * @param list  排序集合
     * @param field 排序字段
     * @param sort  排序方式: ListUtils.DESC(降序) ListUtils.ASC(升序).
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> sort(List<T> list, final String field, final String sort) {
        if (isEmpty(list)) {
            return list;
        }
        Collections.sort(list, new Comparator() {
            @Override
            public int compare(Object a, Object b) {
                int ret = 0;
                try {
                    Field f = a.getClass().getDeclaredField(field);
                    f.setAccessible(true);
                    Class<?> type = f.getType();
                    if (type == int.class) {
                        ret = ((Integer) f.getInt(a)).compareTo((Integer) f.getInt(b));
                    } else if (type == double.class) {
                        ret = ((Double) f.getDouble(a)).compareTo((Double) f.getDouble(b));
                    } else if (type == long.class) {
                        ret = ((Long) f.getLong(a)).compareTo((Long) f.getLong(b));
                    } else if (type == float.class) {
                        ret = ((Float) f.getFloat(a)).compareTo((Float) f.getFloat(b));
                    } else if (type == Date.class) {
                        ret = ((Date) f.get(a)).compareTo((Date) f.get(b));
                    } else if (isImplementsOf(type, Comparable.class)) {
                        ret = ((Comparable) f.get(a)).compareTo((Comparable) f.get(b));
                    } else {
                        ret = String.valueOf(f.get(a)).compareTo(String.valueOf(f.get(b)));
                    }

                } catch (SecurityException e) {
                    e.printStackTrace();
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
                if (sort != null && sort.toLowerCase().equals(DESC)) {
                    return -ret;
                } else {
                    return ret;
                }

            }
        });
        return list;
    }

    /**
     * 对list中的元素按fields和sorts进行排序,
     * fields[i]指定排序字段,sorts[i]指定排序方式.如果sorts[i]为空则默认按升序排列.
     *
     * @param list
     * @param fields
     * @param sorts
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> sort(List<T> list, String[] fields, String[] sorts) {
        if (fields != null && fields.length > 0) {
            for (int i = fields.length - 1; i >= 0; i--) {
                final String field = fields[i];
                String tmpSort = ASC;
                if (sorts != null && sorts.length > i && sorts[i] != null) {
                    tmpSort = sorts[i];
                }
                final String sort = tmpSort;
                Collections.sort(list, new Comparator() {
                    @Override
                    public int compare(Object a, Object b) {
                        int ret = 0;
                        try {
                            Field f = a.getClass().getDeclaredField(field);
                            f.setAccessible(true);
                            Class<?> type = f.getType();
                            if (type == int.class) {
                                ret = ((Integer) f.getInt(a)).compareTo((Integer) f.getInt(b));
                            } else if (type == double.class) {
                                ret = ((Double) f.getDouble(a)).compareTo((Double) f.getDouble(b));
                            } else if (type == long.class) {
                                ret = ((Long) f.getLong(a)).compareTo((Long) f.getLong(b));
                            } else if (type == float.class) {
                                ret = ((Float) f.getFloat(a)).compareTo((Float) f.getFloat(b));
                            } else if (type == Date.class) {
                                ret = ((Date) f.get(a)).compareTo((Date) f.get(b));
                            } else if (isImplementsOf(type, Comparable.class)) {
                                ret = ((Comparable) f.get(a)).compareTo((Comparable) f.get(b));
                            } else {
                                ret = String.valueOf(f.get(a)).compareTo(String.valueOf(f.get(b)));
                            }

                        } catch (SecurityException e) {
                            e.printStackTrace();
                        } catch (NoSuchFieldException e) {
                            e.printStackTrace();
                        } catch (IllegalArgumentException e) {
                            e.printStackTrace();
                        } catch (IllegalAccessException e) {
                            e.printStackTrace();
                        }

                        if (sort != null && sort.toLowerCase().equals(DESC)) {
                            return -ret;
                        } else {
                            return ret;
                        }
                    }
                });
            }
        }
        return list;
    }

    /**
     * 判断对象实现的所有接口中是否包含szInterface
     *
     * @param clazz
     * @param szInterface
     * @return
     */
    private static boolean isImplementsOf(Class<?> clazz, Class<?> szInterface) {
        boolean flag = false;

        Class<?>[] face = clazz.getInterfaces();
        for (Class<?> c : face) {
            if (c == szInterface) {
                flag = true;
            } else {
                flag = isImplementsOf(c, szInterface);
            }
        }

        if (!flag && null != clazz.getSuperclass()) {
            return isImplementsOf(clazz.getSuperclass(), szInterface);
        }

        return flag;
    }


    private static <T> boolean equal(T a, Object b, String... fieldNams) {
        if (a == b) return true;
        if (b == null || a.getClass() != b.getClass()) return false;
        T t2 = (T) b;
        T t1 = (T) a;

        EqualsBuilder equalsBuilder = new EqualsBuilder();
        for (String fieldNam : fieldNams) {
            equalsBuilder.append(getValueOfGet(t1, fieldNam), getValueOfGet(t2, fieldNam));
        }
        return equalsBuilder.isEquals();
    }

    /******************************************
     ***********  工具,反射相关  ***************
     ******************************************/

    /**
     * 通过字段名从对象或对象的父类中得到字段的值
     *
     * @param object    对象实例
     * @param fieldName 字段名
     * @return 字段对应的值
     * @throws Exception
     */
    private static Object getValue(Object object, String fieldName) throws Exception {
        if (object == null) {
            return null;
        }
        if (StringUtils.isBlank(fieldName)) {
            return null;
        }
        Field field = null;
        Class<?> clazz = object.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);
                return field.get(object);
            } catch (Exception e) {

            }
        }
        return null;
    }


    /**
     * 通过字段名从对象或对象的父类中得到字段的值(调用字典的get方法)
     *
     * @param object    对象实例
     * @param fieldName 字段名
     * @return 字段对应的值
     */
    private static Object getValueOfGet(Object object, String fieldName) {
        if (object == null) {
            return null;
        }
        if (StringUtils.isBlank(fieldName)) {
            return null;
        }
        Field field = null;
        Class<?> clazz = object.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                field = clazz.getDeclaredField(fieldName);
                field.setAccessible(true);

                PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                //获得get方法
                Method getMethod = pd.getReadMethod();
                //执行get方法返回一个Object
                return getMethod.invoke(object);
            } catch (Exception e) {

            }
        }
        return null;
    }

    /**
     * 通过字段名数组从对象或对象的父类中得到字段的值(调用字典的get方法)
     *
     * @param object     对象实例
     * @param fieldNames 字段名
     * @return 字段对应的值
     */
    private static Object getValuesOfGet(Object object, String spit, String... fieldNames) {
        if (object == null) {
            return null;
        }
        for (String fieldName : fieldNames) {
            if (StringUtils.isBlank(fieldName)) {
                return null;
            }
        }
        Field field = null;
        Class<?> clazz = object.getClass();
        for (; clazz != Object.class; clazz = clazz.getSuperclass()) {
            try {
                String values = "";
                for (String fieldName : fieldNames) {
                    field = clazz.getDeclaredField(fieldName);
                    field.setAccessible(true);

                    PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                    //获得get方法
                    Method getMethod = pd.getReadMethod();
                    //执行get方法返回一个Object
                    values += spit + getMethod.invoke(object);
                }
                return values.substring(spit.length());
            } catch (Exception e) {

            }
        }
        return null;
    }
}

工具类的使用

indexOf

单字段

public void indexOf1(List list){
    User user = new User();
    user.setUsername("ww");
    int i = ListUtils.indexOf(list, user, (a,b)->{
        User t1 = (User) a;
        User t2 = (User) b;
        return t1.getUsername().equals(t2.getUsername());
    });
    System.out.println(i);
}
// output: 2
public void indexOf2(List list){
    int i = ListUtils.indexOf(list, "ww", (a,b)->{
        User t = (User) a;
        return t.getUsername().equals(b);
    });
    System.out.println(i);
}
// output: 2
public void indexOf3(List list){
    User user = new User();
    user.setUsername("ls");
    int i = ListUtils.indexOf(list, user, "username");
    System.out.println(i);
}
// output: 1

多字段

public void indexOf1(List list) {
    User user = new User();
    user.setUsername("ww");
    user.setNickname("王五");
    int i = ListUtils.indexOf(list, user, (a, b) -> {
        User t1 = (User) a;
        User t2 = (User) b;
        boolean equals = new EqualsBuilder()
            .append(t1.getUsername(), t2.getUsername())
            .append(t1.getNickname(), t2.getNickname())
            .isEquals();
        return equals;
    });
    System.out.println(i);
}
// output: 2
public void indexOf2(List list) {
    int i = ListUtils.indexOf(list, "ww;王五", (a, b) -> {
        User t = (User) a;
        return b.equals(t.getUsername() + ";" + t.getNickname());
    });
    System.out.println(i);
}
// output: 2
public void indexOf3(List list) {
    User user = new User();
    user.setUsername("ls");
    user.setNickname("李四");
    int i = ListUtils.indexOf(list, user, "username", "nickname");
    System.out.println(i);
}
// output: 1

判空

public void isEmpty() {
    List<String> list1 = null;
    List<String> list2 = new ArrayList<>();
    boolean b1 = ListUtils.isEmpty(list1); //java.lang.NullPointerException
    boolean b2 = ListUtils.isEmpty(list2); //true
    System.out.println(b1); 
    System.out.println(b2);
}

public void isNullEmpty() {
    List<String> list1 = null;
    List<String> list2 = new ArrayList<>();
    boolean b1 = ListUtils.isNullEmpty(list1); //true
    boolean b2 = ListUtils.isNullEmpty(list2); //true
    System.out.println(b1);
    System.out.println(b2);
}

判包含

单字段

public void isContains1(List list) {
    User user = new User();
    user.setUsername("ww");
    boolean bool = ListUtils.isContains(list, (a,b)->{
        User t1 = (User) a;
        User t2 = (User) b;
        return t1.getUsername().equals(t2.getUsername());
    },user);
    System.out.println(bool);
}
public void isContains2(List list) {
    boolean bool = ListUtils.isContains(list, User::getUsername,"ww");
    System.out.println(bool);
}
public void isContains3(List list) {
    boolean bool = ListUtils.isContains(list, (a,b)->{
        User t = (User) a;
        String t2 = (String) b;
        return t.getUsername().equals(t2);
    }, "ww");
    System.out.println(bool);
}
public void isContains4(List list) {
    User user = new User();
    user.setUsername("ww");
    boolean bool = ListUtils.isContains(list, user, "username");
    System.out.println(bool);
}

多字段

public void isContains1(List list) {
    User user = new User();
    user.setUsername("ww");
    user.setNickname("王五");
    boolean bool = ListUtils.isContains(list, (a, b) -> {
        User t1 = (User) a;
        User t2 = (User) b;
        boolean equals = new EqualsBuilder()
            .append(t1.getUsername(), t2.getUsername())
            .append(t1.getNickname(), t2.getNickname())
            .isEquals();
        return equals;
    }, user);
    System.out.println(bool);
}
public void isContains2(List<User> list) {
    boolean bool = ListUtils.isContains(list, e -> e.getUsername() + ";" + e.getNickname(), "ww;王五");
    System.out.println(bool);
}
public void isContains3(List list) {
    boolean bool = ListUtils.isContains(list, (a, b) -> {
        User t = (User) a;
        String t2 = (String) b;
        return t2.equals(t.getUsername() + ";" + t.getNickname());
    }, "ww;王五");
    System.out.println(bool);
}
public void isContains4(List list) {
    User user = new User();
    user.setUsername("ww");
    user.setNickname("王五");
    boolean bool = ListUtils.isContains(list, user, "username", "nickname");
    System.out.println(bool);
}

判重

单字段

public void isRepeat1(List list) {
    boolean bool = ListUtils.isRepeat(list, (a, b) -> {
        User t1 = (User) a;
        User t2 = (User) b;
        return t1.getUsername().equals(t2.getUsername());
    });
    System.out.println(bool);
}
public void isRepeat2(List<User> list) {
    boolean bool = ListUtils.isRepeat(list, User::getUsername);
    System.out.println(bool);
}
public void isRepeat3(List list) {
    boolean bool = ListUtils.isRepeat(list, "username");
    System.out.println(bool);
}

多字段

public void isRepeat1(List list) {
    boolean bool = ListUtils.isRepeat(list, (a, b) -> {
        User t1 = (User) a;
        User t2 = (User) b;
        boolean equals = new EqualsBuilder()
            .append(t1.getUsername(), t2.getUsername())
            .append(t1.getPassword(), t2.getPassword())
            .isEquals();
        return equals;
    });
    System.out.println(bool);
}
public void isRepeat2(List<User> list) {
    boolean bool = ListUtils.isRepeat(list, e -> e.getUsername() + ";" + e.getPassword());
    System.out.println(bool);
}
public void isRepeat3(List list) {
    boolean bool = ListUtils.isRepeat(list, "username", "password");
    System.out.println(bool);
}

去重

单字段

public void removeRepeat1(List<User> list) {
    List<User> userList1 = ListUtils.removeRepeat(list, (a, b) -> {
        User t1 = (User) a;
        User t2 = (User) b;
        return t1.getUsername().equals(t2.getUsername());
    }, true);
    List<User> userList2 = ListUtils.removeRepeat(list, (a, b) -> {
        User t1 = (User) a;
        User t2 = (User) b;
        return t1.getUsername().equals(t2.getUsername());
    }, false);
    ListUtils.toStr(userList1, true);
    ListUtils.toStr(userList2, true);
}
public void removeRepeat2(List<User> list) {
    List<User> userList1 = ListUtils.removeRepeat(list, User::getUsername, true);
    List<User> userList2 = ListUtils.removeRepeat(list, User::getUsername, false);
    ListUtils.toStr(userList1, true);
    ListUtils.toStr(userList2, true);
}
public void removeRepeat3(List list) {
    List<User> userList1 = ListUtils.removeRepeat(list, true,"username");
    List<User> userList2 = ListUtils.removeRepeat(list, false,"username");
    ListUtils.toStr(userList1, true);
    ListUtils.toStr(userList2, true);
}
public void removeRepeat4(List list) {
    List<User> userList1 = ListUtils.removeRepeat(list, ";","username");
    ListUtils.toStr(userList1, true);
}

多字段

public void removeRepeat1(List<User> list) {
    List<User> userList1 = ListUtils.removeRepeat(list, (a, b) -> {
        User t1 = (User) a;
        User t2 = (User) b;
        boolean equals = new EqualsBuilder()
            .append(t1.getUsername(), t2.getUsername())
            .append(t1.getPassword(), t2.getPassword())
            .isEquals();
        return equals;
    }, true);
    List<User> userList2 = ListUtils.removeRepeat(list, (a, b) -> {
        User t1 = (User) a;
        User t2 = (User) b;
        boolean equals = new EqualsBuilder()
            .append(t1.getUsername(), t2.getUsername())
            .append(t1.getPassword(), t2.getPassword())
            .isEquals();
        return equals;
    }, false);
    ListUtils.toStr(userList1, true);
    ListUtils.toStr(userList2, true);
}
public void removeRepeat2(List<User> list) {
    List<User> userList1 = ListUtils.removeRepeat(list, e -> e.getUsername() + ";" + e.getPassword(), true);
    List<User> userList2 = ListUtils.removeRepeat(list, e -> e.getUsername() + ";" + e.getPassword(), false);
    ListUtils.toStr(userList1, true);
    ListUtils.toStr(userList2, true);
}
public void removeRepeat3(List list) {
    List<User> userList1 = ListUtils.removeRepeat(list, true, "username", "password");
    List<User> userList2 = ListUtils.removeRepeat(list, false, "username", "password");
    ListUtils.toStr(userList1, true);
    ListUtils.toStr(userList2, true);
}
public void removeRepeat4(List list) {
    List<User> userList1 = ListUtils.removeRepeat(list, ";", "username", "password");
    ListUtils.toStr(userList1, true);
}

查重

单字段

public void findRepeat(List list) {
    List<User> userList = ListUtils.findRepeat(list, "username");
    ListUtils.toStr(userList, true);
}

多字段

public void findRepeat(List list) {
    List<User> userList = ListUtils.findRepeat(list, "username", "password");
    ListUtils.toStr(userList, true);
}

排序

单字段

public void sort1(List list) {
    List<User> userList = ListUtils.sort(list, "id", "desc");
    ListUtils.toStr(userList, true);
}
public void sort2(List list) {
    List<User> userList = ListUtils.sort(list, "age");
    ListUtils.toStr(userList, true);
}

多字段

public void sort(List list) {
    List<User> userList = ListUtils.sort(list, new String[]{"age","id"}, new String[]{"asc","desc"});
    ListUtils.toStr(userList, true);
}
posted @ 2020-12-08 22:43  Lomen~  阅读(185)  评论(0编辑  收藏  举报