Java对List中的中文属性按照拼音排序

来源:互联网 发布:手机电影网php源码 编辑:程序博客网 时间:2024/05/15 12:53

比较简单的问题,可以用Collections.sort()来进行排序
一般情况下我们会这样做;

 private static final List<TestEntity> testEntities = new ArrayList<TestEntity>();    static {        testEntities.add(new TestEntity("李循环", 12));        testEntities.add(new TestEntity("张小刘", 12));        testEntities.add(new TestEntity("红旗", 15));    }    @Test    public void  listSortByName(){        Collections.sort(testEntities, new Comparator<TestEntity>() {            @Override            public int compare(TestEntity o1, TestEntity o2) {                return o1.getName().compareTo(o2.getName());            }        });        for (TestEntity testEntity:testEntities) {            System.out.println(testEntity.toString());        }    }

输出结果:
name:张小刘 age:12
name:李循环 age:12
name:红旗 age:15
注意:并不是按照中文拼音的顺序,原因是Collator 类执行区分语言环境的 String 比较。使用此类可为自然语言文本构建搜索和排序例程。 若要针对不同语言,java提供Collator来处理。Collator 是一个抽象基类。其子类实现具体的整理策略。Java 平台目前提供了 RuleBasedCollator 子类,它适用于很多种语言。还可以创建其他子类,以处理更多的专门需要。 与其他区分语言环境的类一样,可以使用静态工厂方法 getInstance 来为给定的语言环境获得适当的 Collator 对象。如果需要理解特定整理策略的细节或者需要修改策略,只需查看 Collator 的子类即可。
如:

@Test    public void  listSortByName1(){        Collections.sort(testEntities, new Comparator<TestEntity>() {            @Override            public int compare(TestEntity o1, TestEntity o2) {                return Collator.getInstance(Locale.CHINESE).compare(o1.getName(),o2.getName());            }        });        for (TestEntity testEntity:testEntities) {            System.out.println(testEntity.toString());        }    }

结果为:
name:红旗 age:15
name:李循环 age:12
name:张小刘 age:12

问题解决了,但是这段代码看起来很不舒服,java 8中提供Lambda表达式,不仅可以使代码简洁,还能提高效率:

  @Test    public void  listSortByName2(){        Collections.sort(testEntities,(TestEntity o1,TestEntity o2)-> Collator.getInstance(Locale.CHINESE).compare(o1.getName(),o2.getName()));        testEntities.forEach((TestEntity t)->System.out.println(t.toString()));    }

结果为:
name:红旗 age:15
name:李循环 age:12
name:张小刘 age:12

原创粉丝点击