java set排序_Java Set元素 排序

Set排序

set包括HashSet和TreeSet,HashSet是基于HashMap的,TreeSet是基于TreeMap的。

TreeMap是用红黑树实现,天然就具有排序功能,“天然就具有排序功能”是指它拥有升序、降序的迭代器。

那么HashSet怎么排序呢?我们可以将HashSet转成List,然后用List进行排序。

例如:

package SetLearn;

public class User implements Comparable {

private String name;

private int age;

public User() {

}

public User(String name, int age) {

super();

this.name = name;

this.age = age;

}

@Override

public String toString() {

return "name:" + name + ",age:" + age;

}

public String getName() {

return name;

}

public void setName(String name) {

this.name = name;

}

public int getAge() {

return age;

}

public void setAge(int age) {

this.age = age;

}

@Override

public int compareTo(User o) {

if (o.age < this.age) {

return 1;

} else if (o.age > this.age) {

return -1;

} else {

return 0;

}

}

/**

* @param args

*/

public static void main(String[] args) {

User u1 = new User("fox", 11);

User u2 = new User("fox2", 21);

System.out.println(u2.compareTo(u1));

}

}

主要示例代码:

Set us = new HashSet();

//Set us = new TreeSet();

//Set us = new TreeSet(new Comparator() {

//@Override

//public int compare(User o1, User o2) {

//if (o1.getAge() < o2.getAge()) {

//return -1;

//} else if (o1.getAge() > o2.getAge()) {

//return 1;

//} else {

//return o1.getName().compareTo(o2.getName());

//}

//}

//});

us.add(new User("f5", 12));

us.add(new User("f2", 22));

us.add(new User("f3", 2));

us.add(new User("f4", 14));

us.add(new User("f5", 32));

us.add(new User("f4", 12));

us.add(new User("f7", 17));

us.add(new User("f8", 52));

// set -> array

List list = new ArrayList(us);

System.out.println(list);

Collections.sort(list);

System.out.println(list);

也可以将HashSet转换成数组用Arrays排序。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值