java 根據 ASCII 碼表順序升序排列


原理通過sort()方法排序。

 

/**
 * 反射拼接類的屬性值
 *
 * @return
 */
private String getAscOrderString() {
    Object object = this;
    String rawString = "";
    Map<String, String> map = new HashMap<String, String>();

    //獲取所有的屬性組
    Field[] superField = this.getClass().getSuperclass().getDeclaredFields();
    Field[] selfField = this.getClass().getDeclaredFields();

    List<Field> allfield = new ArrayList();

    allfield.addAll(Arrays.stream(superField).collect(Collectors.toList()));
    allfield.addAll(Arrays.stream(selfField).collect(Collectors.toList()));

    for (int i = 0; i < allfield.size(); i++) {
        Field field = allfield.get(i);
        String fieldName = field.getName();
        if (Objects.nonNull(field.getAnnotation(JSONField.class))) {
            fieldName = field.getAnnotation(JSONField.class).name();
        }
        field.setAccessible(true);
        String valString;
        try {
            if (field.get(object) == null) {
                valString = "";
            } else {
                valString = field.get(object).toString();
            }
            map.put(fieldName, valString);
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    Collection<String> keyset = map.keySet();
    List list = new ArrayList<String>(keyset);
    Collections.sort(list);
    for (int i = 0; i < list.size(); i++) {
        if (i == (list.size() - 1)) {
            if (!StringUtils.isEmpty(map.get(list.get(i)))) {
                rawString += list.get(i) + "=" + map.get(list.get(i));
            }
        } else {
            if (!StringUtils.isEmpty(map.get(list.get(i)))) {
                rawString += list.get(i) + "=" + map.get(list.get(i)) + "&";
            }
        }
    }
    return rawString;
}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM