自定义排序,字符串排序,Comparator

    //既定顺序
    List<String> sortStrings = Arrays.asList("香蕉", "苹果", "梨子", "芒果", "橙子");
    //需要排序
    List<String> needToSort = Arrays.asList("苹果", "香蕉", "苹果", "橙子", "芒果","梨子");
    //通过对比 需要比较元素在ArrayList的index 就可以得到比较方法
    //比for循环简洁
    List<String> stringList=needToSort.stream().sorted(Comparator.comparingInt(sortStrings::indexOf)).collect(Collectors.toList());
    //输出
    sortStrings.forEach(System.out::print);
    System.out.println("");
    needToSort.forEach(System.out::print);
    System.out.println("");
    stringList.forEach(System.out::print);

posted @ 2020-03-02 22:53  onexixi  阅读(1454)  评论(0编辑  收藏  举报