Java实现List中某个对象属性中的字符串参数首字母进行排序

  public static void main(String[] args) {
     //数组 中文首字母排序
        // Collator 类是用来执行区分语言环境的 String 比较的,这里选择使用CHINA
        Comparator comparator = Collator.getInstance(Locale.CHINA);
        String[] arrStrings = {"乔峰", "郭靖", "杨过", "张无忌", "韦小宝"};
        // 使根据指定比较器产生的顺序对指定对象数组进行排序。
        Arrays.sort(arrStrings, comparator);


        //List<对象> 中文首字母排序
        List<SysUserMember> list = 获取这个list;
        // Collator 类是用来执行区分语言环境的 String 比较的,这里选择使用CHINA
        Comparator comparator = Collator.getInstance(Locale.CHINA);
        Collections.sort(list, (o1, o2) -> comparator.compare(o1.getMemberUnitName(), o2.getMemberUnitName()));
        list.stream().forEach(System.out::println);

        //List<String> 中文首字母排序
        List<String> list = new ArrayList();
        list.add("李");
        list.add("张");
        list.add("胡");
        // Collator 类是用来执行区分语言环境的 String 比较的,这里选择使用CHINA
        Collator comparator = Collator.getInstance(Locale.CHINESE);
        Collections.sort(list, (o1, o2) -> comparator.compare(o1, o2));


        //List<对象或者String> 字符串首个字符字母排序
      需要导入
      <!-- PinyinHelper汉字拼音转换 start-->
      <dependency>
        <groupId>com.belerweb</groupId>
        <artifactId>pinyin4j</artifactId>
        <version>2.5.1</version>
      </dependency>
      <!-- PinyinHelper汉字拼音转换 start-->

        List<Employee> employees = Arrays.asList(
                new Employee("陈", 18, 1),
                new Employee("only服饰", 37, 2),
                new Employee("一丢丢", 50, 3),
                new Employee("gAP集团", 8, 5)
        );
        employees.sort((v1, v2) -> {
            char[] chars1 = v1.getName().toCharArray();
            char[] chars2 = v2.getName().toCharArray();
            String c1 = Character.toString(chars1[0]);
            String c2 = Character.toString(chars2[0]);
            if (Character.toString(chars1[0]).matches("[\\u4E00-\\u9FA5]+")) {
                c1 = PinyinHelper.toHanyuPinyinStringArray(chars1[0])[0];
            }
            if (Character.toString(chars2[0]).matches("[\\u4E00-\\u9FA5]+")) {
                c2 = PinyinHelper.toHanyuPinyinStringArray(chars2[0])[0];
            }
            return c1.compareTo(c2);
        });
        employees.stream().forEach(System.out::println);
    }

  如果解决了你的问题帮忙关注下,谢谢
 

 

posted @ 2020-12-31 10:51  暖瞳123  阅读(3213)  评论(0编辑  收藏  举报