java-按字符串长度排序

在这里插入图片描述

package com.vector;

import java.util.Comparator;
import java.util.Iterator;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args){
        TreeSet ts =new TreeSet(new Comparator() {
            @Override
            public int compare(Object o1, Object o2) {
                int result=  ((String)o1).length()-((String)o2).length()==0?((String) o1).compareTo((String) o2):((String)o1).length()-((String)o2).length();
                return result;
            }
            /**
             * 1.强制转型的优先级低于方法调用的优先级
             * 2.三目判断运算符,解决treeSet去掉重复问题.当长度相同,按字典序排序.
             */

        });
        /**
         * TreeSet的带参构造方法使用的是比较器排序对元素进行排序的
         * 比较器排序.就是让集合构造方法接收Comparetor的实现类对象,重写Compareto(O1,O2)方法
         * 重写方法时,一定要注意排序规则必须按照要求的主要条件和次要条件来写
         */

        ts.add("abc");
        ts.add("fwc");
        ts.add("acwq");
        ts.add("sdg");
        ts.add("agadgv");
        Iterator it = ts.iterator();
        while (it.hasNext()){
            System.out.println(it.next());
        }
       
    }
}




package com.vector;

import java.util.Comparator;
import java.util.TreeSet;

public class Main {
    public static void main(String[] args) {
        TreeSet<Comp> ts = new TreeSet<>(new Comp());
        Comp t1 = new Comp("asc");
        Comp t2 = new Comp("afc");
        Comp t3 = new Comp("sadfas");
        ts.add(t1);
        ts.add(t2);
        ts.add(t3);
        System.out.println(ts);
    }
}

class Comp implements Comparator<Comp>{
    String o;
    public Comp(){

     }
     public Comp(String o){
        this.o= o;
     }

    @Override
    public String toString() {
        return "Comp{" +
                "o='" + o + '\'' +
                '}';
    }

    @Override
    public int compare(Comp o1, Comp o2) {
        int result =o1.o.length()-o2.o.length()==0?o1.o.compareTo(o2.o):o1.o.length()-o2.o.length();
        return result;
    }
}





  • 0
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

最难不过坚持丶渊洁

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值