用TreeSet存储以下数据:
“xiaoqiang”、 “zhangsan”、“lisi”、“xiaohua”、 “ruhua”、 “wangcai”
要求按照字符串的长度进行排序后再存储(如果长度相同,则按字符串的自然顺序排序)
package com.Work4;/*** @Author: 廾匸* @Date: 2020/11/22 19:14* @Description:* @version: 1.01*/
import org.junit.Test;import java.util.Comparator;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;public class Sor {
@Testpublic void test(){
TreeMap<String,Integer> treeMap = new TreeMap<>(new Comparator<String>() {
@Overridepublic int compare(String o1, String o2) {
if(o1.length() != o2.length()){
return o1.length() - o2.length();}int i = o1.compareTo(o2);if(i!=0){
return i;}return 0;}});treeMap.put("xiaoqiang",1);treeMap.put("zhangsan",2);treeMap.put("lisi",3);treeMap.put("xiaohua",4);treeMap.put("ruhua",5);treeMap.put("wangcai",6);Set<String> strings = treeMap.keySet();Iterator<String> iterator = strings.iterator();while(iterator.hasNext()){
System.out.println(iterator.next());}}
}