日期:2014-05-20 浏览次数:20680 次
import java.text.Collator; import java.util.Collections; import java.util.Comparator; import java.util.Locale; import java.util.Vector; public class PlayerUtil { static Collator collator = Collator.getInstance(Locale.CHINA); static{ collator.setStrength(Collator.SECONDARY); collator.setDecomposition(Collator.NO_DECOMPOSITION); } /** * 根据球队队员Name排序,对大小不敏感 * * @param players */ public static void sortByName(Vector<Player> players){ if(players == null || players.isEmpty()) return; Collections.sort(players, new Comparator<Player>() { @Override public int compare(Player player1, Player player2) { return collator.compare(player1.getName(), player2.getName()); } }); } /** * 根据球队队员Number排序,按字典顺序排序 * * @param players */ public static void sortByNumber(Vector<Player> players){ if(players == null || players.isEmpty()) return; Collections.sort(players, new Comparator<Player>() { @Override public int compare(Player player1, Player player2) { return player1.getNumber().compareTo(player2.getNumber()); } }); } /** * 根据球队队员Position排序,对大小不敏感 * * @param players */ public static void sortByPosition(Vector<Player> players){ if(players == null || players.isEmpty()) return; Collections.sort(players, new Comparator<Player>() { @Override public int compare(Player player1, Player player2) { return collator.compare(player1.getPosition(), player2.getPosition()); } }); } /** * 打印结果 * * @param players */ public static void display(Vector<Player> players){ if(players == null || players.isEmpty()) return; for(Player player : players){ System.out.println(player); } } public static void main(String[] args) { Vector<Player> players = new Vector<Player>(); players.add(new Player(5,"Center","ABC")); players.add(new Player(1,"Guard","DEF")); players.add(new Player(9,"Forward","GHI")); players.add(new Player(6,"guard","abc")); players.add(new Player(4,"FORWARD","Defcf")); players.add(new Player(2,"Guard","ghif")); System.out.println("-------------------Sort by Number : "); PlayerUtil.sortByNumber(players); PlayerUtil.display(players); System.out.println("-------------------End"); System.out.println("-------------------Sort by Name : "); PlayerUtil.sortByName(players); PlayerUtil.display(players); System.out.println("-------------------End"); System.out.println("-------------------Sort by Position : "); PlayerUtil.sortByPosition(players); PlayerUtil.display(players); System.out.println("-------------------End"); } } class Player{ private Integer number; private String name; private String position; public Player(Integer number, String name, String position){ this.number = number; this.name = name; this.position = position; } public Integer getNumber() { return number; } public String getName() { return name; } public String getPosition() { return position; } @Override public String toString() { return "Player [number=" + number + ", name=" + name + ", position=" + position + "]"; } }