TreeSet使用示例

package com.jeremy.set;

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

public class SortedTeam {

	public static void main(String[] args){
		
		SortedSet<Player> sortedSet = new TreeSet<>();
		sortedSet.add(new Player("Jhone", 20));
		sortedSet.add(new Player("Jhone1", 25));
		sortedSet.add(new Player("Jhone2", 2));
		sortedSet.add(new Player("Jhone3", 29));
		System.out.println("================ 默认按照类声明的方式排序 按年龄排序 ================");
		printSet(sortedSet);
		
		SortedSet<Player> sortedSet2 = new TreeSet<>(new Comparator<Player>() {

			@Override
			public int compare(Player o1, Player o2) {
				// TODO Auto-generated method stub
				return o1.getName().compareTo(o2.getName());
			}
			
		});
		sortedSet2.addAll(sortedSet);
		
		System.out.println("=========== 按照set指定的规则排序 按照姓名排序 =====================");
		
		printSet(sortedSet2);
		
	}
	

	
	private static void printSet(Set<Player> set){
		Iterator<Player> iterator = set.iterator();
		while (iterator.hasNext()) {
			SortedTeam.Player player = (SortedTeam.Player) iterator.next();
			System.out.println(player.getName() + "  " + player.getAge() + "\r\n");
		}
	}
	
	
	private static class Player implements Comparable<Player>{
		
		/**
		 * @return the name
		 */
		public String getName() {
			return name;
		}





		/**
		 * @return the age
		 */
		public int getAge() {
			return age;
		}





		private String name;
		private int age;
		
		

		public Player(String name, int age) {
			super();
			this.name = name;
			this.age = age;
		}
		
		



		@Override
		public int compareTo(Player o) {
			// TODO Auto-generated method stub
			return age - o.getAge();
		}
		
	}
	
}

你可能感兴趣的:(java,iterator,TreeSet,数据类型结构)