提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
使用sortedset和TreeSets。
import java.util.Arrays; import java.util.SortedSet; import java.util.TreeSet; /* n o w j a v a . c o m 提供 */ public class Main { public static void main(String[] args) { // create TreeSet from array colors String[] colors = {"yellow", "green", "black", "tan", "grey", "white", "orange", "red", "green"}; SortedSet<String> tree = new TreeSet<>(Arrays.asList(colors)); /* *来 自 n o w j a v a . c o m */ System.out.print("sorted set: "); printSet(tree); // get headSet based on "orange" System.out.print("headSet (\"orange\"): "); printSet(tree.headSet("orange")); // get tailSet based upon "orange" System.out.print("tailSet (\"orange\"): "); printSet(tree.tailSet("orange")); // get first and last elements System.out.printf("first: %s%n", tree.first()); System.out.printf("last : %s%n", tree.last()); }