美文网首页
一维数组转变为二维数组并进行排序

一维数组转变为二维数组并进行排序

作者: 晓晓罗 | 来源:发表于2021-03-22 11:34 被阅读0次

在现实情况中,我们会遇到这样的情况,从后台服务器拿到的数据是一个一维数组,但是我们显示的时候要分类显示(如:需要按照月份来分类显示列表),这个时候就需要把一维数组转换为二维数组,方便我们将数据显示出来。如果每一次都重新写转换的方法细节,那将浪费很多时间在重复的代码上面。

后面为了省时间,就花了半天时间,写出来下面的工具类,方便数据转换为所需的格式,同时进行数据排序。

下面先把代码放出来:

1.编写一个List,Set,Map转换的帮助类(CollectionUtils)

public class CollectionUtils {
    /**
     * List转set
     *
     * @param list
     * @param <T>
     * @return
     */
    public static <T> Set<T> getSetByList(List<T> list) {
        Set<T> result = new HashSet<>(list);
        return result;
    }

    /**
     * set转list
     *
     * @param setArrs
     * @param <T>
     * @return
     */
    public static <T> List<T> getListBySet(Set<T> setArrs) {
        ArrayList<T> result = new ArrayList<T>(setArrs);
        return result;
    }

    /**
     * map转list,不排序
     *
     * @param map
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K, V> List<V> getListByMap(Map<K, V> map) {
        return getListByMap(map, null);
    }

    /**
     * map转list,排序
     *
     * @param map
     * @param <K>
     * @param <V>
     * @return
     */
    public static <K, V> List<V> getListByMap(Map<K, V> map, Comparator<V> comparator) {
        ArrayList<V> result = new ArrayList<V>();
        for (V value : map.values()) {
            result.add(value);
        }
        if (comparator != null) {
            //进行排序
            Collections.sort(result, comparator);
        }
        return result;
    }

    /**
     * list转map,key为Integer,不排序
     *
     * @param list
     * @param <V>
     * @return
     */
    public static <V> Map<Integer, V> getMapByList(List<V> list) {
        return getMapByList(list, null);
    }

    /**
     * list转map,key为Integer,排序
     *
     * @param list
     * @param <V>
     * @return
     */
    public static <V> Map<Integer, V> getMapByList(List<V> list, Comparator<V> comparator) {
        if (comparator != null) {
            //进行排序
            Collections.sort(list, comparator);
        }
        if (list != null && list.size() > 0) {
            Map<Integer, V> result = new HashMap<>();
            for (int i = 0; i < list.size(); i++) {
                result.put(i, list.get(i));
            }
            return result;
        }
        return null;
    }
}

2.编写静态帮助类(AbsTwoDimensionalArrayUtils)

public abstract class AbsTwoDimensionalArrayUtils<K, V> {
    //升序(从小到大)
    public static final int ASC_TYPE = 0;
    //降序(从大到小)
    public static final int DESC_TYPE = 1;

    protected Class<K> kClass;

    public AbsTwoDimensionalArrayUtils(Class<K> kClass) {
        this.kClass = kClass;
    }

    /**
     * 获取排序后的二维数组
     *
     * @param dataArrays
     * @return
     */
    public List<List<V>> getTwoDimensionalArrayByList(List<V> dataArrays) {
        Map<K, List<V>> mapByList = getMapByList(dataArrays);
        List<List<V>> result = null;
        //排序小组的顺序
        Comparator<Map.Entry<K, List<V>>> keyComparator = getKeyListComparator();
        if (keyComparator != null) {
            result = new ArrayList<>();
            List<Map.Entry<K, List<V>>> list = new ArrayList<Map.Entry<K, List<V>>>(mapByList.entrySet());
            Collections.sort(list, keyComparator);
            for (int i = 0; i < list.size(); i++) {
                result.add(list.get(i).getValue());
            }
            System.out.println("end time " + System.currentTimeMillis());
        } else {
            //直接转换
            result = CollectionUtils.getListByMap(mapByList);
        }
        return result;
    }

    /**
     * 获取HashMap
     *
     * @param dataArrays
     * @return
     */
    public Map<K, List<V>> getMapByList(List<V> dataArrays) {
        System.out.println("start time " + System.currentTimeMillis());
        HashMap<K, List<V>> result = new HashMap<K, List<V>>();
        if (dataArrays != null && dataArrays.size() > 0) {
            K key;
            for (int i = 0; i < dataArrays.size(); i++) {
                V v = dataArrays.get(i);
                key = getKey(v);
                List<V> value;
                if (result.containsKey(key)) {
                    //如果已经有了,就取出来
                    value = result.get(key);
                    value.add(v);
                } else {
                    value = new ArrayList<>();
                    value.add(v);
                }
                result.put(key, value);
            }
        }
        //排序每个组里面的数据
        Comparator<V> valuecomparator = getValueListComparator();
        if (valuecomparator != null) {
            List<V> mapListValue;
            for (Map.Entry<K, List<V>> entry : result.entrySet()) {
                mapListValue = entry.getValue();
                if (mapListValue != null && mapListValue.size() > 0) {
                    Collections.sort(mapListValue, valuecomparator);
                }
            }
        }
        System.out.println("end time " + System.currentTimeMillis());
        return result;
    }


    /**
     * 通过V来实现分组
     *
     * @param v
     * @return
     */
    public abstract K getKey(V v);

    /**
     * 编写key的排序
     * @return
     */
    public abstract Comparator<Map.Entry<K, List<V>>> getKeyListComparator();

    /**
     * 编写value的排序规则
     * 
     * @return
     */
    public abstract Comparator<V> getValueListComparator();
}

3.根据静态帮助类编写key为int和String的帮助类

A.key为Int时

public abstract class AbsIntTwoDimensionalArrayUtils<V> extends AbsTwoDimensionalArrayUtils<Integer, V> {
    protected Class<V> vClass;
    protected Field field;
    protected Method method;

    protected Field sortField;
    protected Method sortMethod;

    public AbsIntTwoDimensionalArrayUtils(Class vClass) {
        super(Integer.class);
        this.vClass = vClass;

        String mapName = getMapKeyName();
        String sortName = getSortName();
        //获取分类字段
        try {
            field = vClass.getField(mapName);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        //获取排序字段
        try {
            sortField = vClass.getField(sortName);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        //获取分类的字段的值的method
        try {
            String firstLetter = mapName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + mapName.substring(1);
            method = vClass.getMethod(getter, new Class[]{});
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取排序的字段的值的method
        try {
            String firstLetterSort = sortName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetterSort + sortName.substring(1);
            sortMethod = vClass.getMethod(getter, new Class[]{});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public Integer getKey(V v) {
        if (field == null) {
            //说明是字段不为public,去寻找get方法
            try {
                return (Integer) method.invoke(v, new Integer[]{});
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            try {
                return field.getInt(v);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    @Override
    public Comparator<Map.Entry<Integer, List<V>>> getKeyListComparator() {
        return new Comparator<Map.Entry<Integer, List<V>>>() {
            @Override
            public int compare(Map.Entry<Integer, List<V>> o1, Map.Entry<Integer, List<V>> o2) {
                if (getMapKeySortType() == ASC_TYPE) {
                    return ascMapKey(o1, o2);
                } else {
                    return descMapkey(o1, o2);
                }
            }
        };
    }

    /**
     * 根据map的key降序排序
     *
     * @param o1
     * @param o2
     * @return
     */
    private Integer descMapkey(Map.Entry<Integer, List<V>> o1, Map.Entry<Integer, List<V>> o2) {
        try {
            if (o1.getKey() > o2.getKey()) {
                return -1;
            }
            if (o1.getKey() < o2.getKey()) {
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 根据map的key升序排序
     *
     * @param o1
     * @param o2
     * @return
     */
    private Integer ascMapKey(Map.Entry<Integer, List<V>> o1, Map.Entry<Integer, List<V>> o2) {
        try {
            if (o1.getKey() < o2.getKey()) {
                return -1;
            }
            if (o1.getKey() > o2.getKey()) {
                return 1;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Comparator<V> getValueListComparator() {
        return new Comparator<V>() {
            @Override
            public int compare(V o1, V o2) {
                if (getSortType() == ASC_TYPE) {
                    return sortAsc(o1, o2);
                } else {
                    return sortDesc(o1, o2);
                }
            }
        };
    }

    /**
     * 降序排序每个子对象
     *
     * @param o1
     * @param o2
     * @return
     */
    private int sortDesc(V o1, V o2) {
        if (sortField == null) {
            try {
                if (isIntSortFiled()) {
                    return ((Integer) sortMethod.invoke(o2, new Integer[]{})).compareTo((Integer) sortMethod.invoke(o1, new Integer[]{}));
                } else {
                    return ((String) sortMethod.invoke(o2, new String[]{})).compareTo((String) sortMethod.invoke(o1, new String[]{}));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            try {
                if (isIntSortFiled()) {
                    if (sortField.getInt(o1) > sortField.getInt(o2)) {
                        return -1;
                    }
                    if (sortField.getInt(o1) < sortField.getInt(o2)) {
                        return 1;
                    }
                } else {
                    return ((String) sortField.get(o2)).compareTo((String) sortField.get(o1));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * 升序排序每个子对象
     *
     * @param o1
     * @param o2
     * @return
     */
    private int sortAsc(V o1, V o2) {
        if (sortField == null) {
            try {
                if (isIntSortFiled()) {
                    return ((Integer) sortMethod.invoke(o1, new Integer[]{})).compareTo((Integer) sortMethod.invoke(o2, new Integer[]{}));
                } else {
                    return ((String) sortMethod.invoke(o1, new String[]{})).compareTo((String) sortMethod.invoke(o2, new String[]{}));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            try {
                if (isIntSortFiled()) {
                    if (sortField.getInt(o1) > sortField.getInt(o2)) {
                        return 1;
                    }
                    if (sortField.getInt(o1) < sortField.getInt(o2)) {
                        return -1;
                    }
                } else {
                    return ((String) sortField.get(o1)).compareTo((String) sortField.get(o2));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * 获取对象的排序字段名
     *
     * @return
     */
    public abstract String getSortName();

    /**
     * 获取map的key字段名
     *
     * @return
     */
    public abstract String getMapKeyName();

    /**
     * 获取每个对象的排序方式(升序/降序)
     *
     * @return
     */
    public abstract int getSortType();

    /**
     * 获取map的key的排序方式(升序/降序)
     *
     * @return
     */
    public abstract int getMapKeySortType();

    /**
     * 对象的字段是否是int类型的排序字段
     *
     * @return
     */
    public abstract boolean isIntSortFiled();
}

B.key为String时

public abstract class AbsStringTwoDimensionalArrayUtils<V> extends AbsTwoDimensionalArrayUtils<String, V> {
    protected Class<V> vClass;
    protected Field field;
    protected Method method;

    protected Field sortField;
    protected Method sortMethod;

    public AbsStringTwoDimensionalArrayUtils(Class vClass) {
        super(String.class);
        this.vClass = vClass;

        String mapName = getMapKeyName();
        String sortName = getSortName();
        //获取分类字段
        try {
            field = vClass.getField(mapName);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        //获取排序字段
        try {
            sortField = vClass.getField(sortName);
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }
        //获取分类的字段的值的method
        try {
            String firstLetter = mapName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + mapName.substring(1);
            method = vClass.getMethod(getter, new Class[]{});
        } catch (Exception e) {
            e.printStackTrace();
        }
        //获取排序的字段的值的method
        try {
            String firstLetterSort = sortName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetterSort + sortName.substring(1);
            sortMethod = vClass.getMethod(getter, new Class[]{});
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getKey(V v) {
        if (field == null) {
            //说明是字段不为public,去寻找get方法
            try {
                return (String) method.invoke(v, new String[]{});
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        } else {
            try {
                return (String) field.get(v);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return "";
    }

    @Override
    public Comparator<Map.Entry<String, List<V>>> getKeyListComparator() {
        return new Comparator<Map.Entry<String, List<V>>>() {
            @Override
            public int compare(Map.Entry<String, List<V>> o1, Map.Entry<String, List<V>> o2) {
                if (getMapKeySortType() == ASC_TYPE) {
                    return ascMapKey(o1, o2);
                } else {
                    return descMapkey(o1, o2);
                }
            }
        };
    }

    /**
     * 根据map的key降序排序
     *
     * @param o1
     * @param o2
     * @return
     */
    private Integer descMapkey(Map.Entry<String, List<V>> o1, Map.Entry<String, List<V>> o2) {
        try {
            return o2.getKey().compareTo(o1.getKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    /**
     * 根据map的key升序排序
     *
     * @param o1
     * @param o2
     * @return
     */
    private Integer ascMapKey(Map.Entry<String, List<V>> o1, Map.Entry<String, List<V>> o2) {
        try {
            return o1.getKey().compareTo(o2.getKey());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return 0;
    }

    @Override
    public Comparator<V> getValueListComparator() {
        return new Comparator<V>() {
            @Override
            public int compare(V o1, V o2) {
                if (getSortType() == ASC_TYPE) {
                    return sortAsc(o1, o2);
                } else {
                    return sortDesc(o1, o2);
                }
            }
        };
    }

    /**
     * 降序排序每个子对象
     *
     * @param o1
     * @param o2
     * @return
     */
    private int sortDesc(V o1, V o2) {
        if (sortField == null) {
            try {
                if (isIntSortFiled()) {
                    return ((Integer) sortMethod.invoke(o2, new Integer[]{})).compareTo((Integer) sortMethod.invoke(o1, new Integer[]{}));
                } else {
                    return ((String) sortMethod.invoke(o2, new String[]{})).compareTo((String) sortMethod.invoke(o1, new String[]{}));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            try {
                if (isIntSortFiled()) {
                    if (sortField.getInt(o1) > sortField.getInt(o2)) {
                        return -1;
                    }
                    if (sortField.getInt(o1) < sortField.getInt(o2)) {
                        return 1;
                    }
                } else {
                    return ((String) sortField.get(o2)).compareTo((String) sortField.get(o1));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * 升序排序每个子对象
     *
     * @param o1
     * @param o2
     * @return
     */
    private int sortAsc(V o1, V o2) {
        if (sortField == null) {
            try {
                if (isIntSortFiled()) {
                    return ((Integer) sortMethod.invoke(o1, new Integer[]{})).compareTo((Integer) sortMethod.invoke(o2, new Integer[]{}));
                } else {
                    return ((String) sortMethod.invoke(o1, new String[]{})).compareTo((String) sortMethod.invoke(o2, new String[]{}));
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }
        } else {
            try {
                if (isIntSortFiled()) {
                    if (sortField.getInt(o1) > sortField.getInt(o2)) {
                        return 1;
                    }
                    if (sortField.getInt(o1) < sortField.getInt(o2)) {
                        return -1;
                    }
                } else {
                    return ((String) sortField.get(o1)).compareTo((String) sortField.get(o2));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return 0;
    }

    /**
     * 获取对象的排序字段名
     *
     * @return
     */
    public abstract String getSortName();

    /**
     * 获取map的key字段名
     *
     * @return
     */
    public abstract String getMapKeyName();

    /**
     * 获取每个对象的排序方式(升序/降序)
     *
     * @return
     */
    public abstract int getSortType();

    /**
     * 获取map的key的排序方式(升序/降序)
     *
     * @return
     */
    public abstract int getMapKeySortType();

    /**
     * 对象的字段是否是int类型的排序字段
     *
     * @return
     */
    public abstract boolean isIntSortFiled();
}

----------------------------------------华丽的分割线----------------------------------------------------------

下面就到了万众期待的使用方式了:

1.根据实际的数据类型,来定义帮助类,如果key是Int,就继承AbsIntTwoDimensionalArrayUtils;如果key是String,就继承AbsStringTwoDimensionalArrayUtils。

下面使用了int类型的例子:

public class TwoDimensionalArrayDemoUtils
        extends AbsIntTwoDimensionalArrayUtils<User> {

    public TwoDimensionalArrayDemoUtils() {
        super(User.class);
    }

    @Override
    public String getSortName() {
        return "name";
    }
    
    @Override
    public int getSortType() {
        return ASC_TYPE;
    }

    @Override
    public int getMapKeySortType() {
        return ASC_TYPE;
    }

    @Override
    public String getMapKeyName() {
        return "age";
    }

    @Override
    public boolean isIntSortFiled() {
        return false;
    }
}

2.数据类型User类如下:

public class User {
    public int id;
    private int age;
    public String name = "";

    public User(int id, int age, String name) {
        this.id = id;
        this.age = age;
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public int getId() {
        return id;
    }

    public String getName() {
        return name;
    }
}

3.调用方式

    TwoDimensionalIntArrayDemoUtils hashMapUtils = new TwoDimensionalIntArrayDemoUtils();
    //获取二维数组
    List<List<User>> lists = hashMapUtils.getTwoDimensionalArrayByList(users);
    //获取HashMap
    Map<Integer, List<User>> mapByList = hashMapUtils.getMapByList(users);

这样操作下来,我们就可以将一个一维数组转换为一个二维数组或者一个Map结构的数据,同时将数据进行排序排序。

相关文章

网友评论

      本文标题:一维数组转变为二维数组并进行排序

      本文链接:https://www.haomeiwen.com/subject/imrzcltx.html