web123456

Various traversal methods of treeMap and the implementation of comparator and comparable

  • public class TreeMapTest {
  • public static void main(String[] args) {
  • Random gradeRandom =new Random();
  • // Generate random numbers to assign different initial values ​​to grade
  • TreeMap<Grade,String> gradeMap=new TreeMap<>(new gradeComparator());
  • //new a TreeMap collection key part is a custom Grade type, and the value part is a comparator for comparison scores passed in String gradeComparator()
  • for (int i = 0; i <1000; i++) {
  • (new Grade((101),"gold"+i),"gold"+i);
  • }
  • // Assign values ​​to the set through a for loop
  • //The following is to traverse TreeMap collection by converting the key part into a Set collection
  • /*Set<Grade> gradeKeys=();//set set is used to store part of key data
  • for(Grade i:gradeKeys)
  • {
  • (i+" "+(i));//Get value through key
  • }*/
  • //The following is to convert the key and value in the TreeMap collection into a Set collection
  • //It is an internal interface in the Map interface. Its generic is the form of the internal class <Grade,Sring>
  • //The generic type of Set is <Grade,String> data type
  • Set<<Grade,String>> its=();
  • /*Iterator<<Grade,String>> itsIterator=();//Transfer the Set collection through an iterator
  • while(()){
  • (());
  • }*/
  • for(<Grade,String> i:its)//Transfer Set collections through enhanced for loop
  • {
  • (i);
  • }
  • }
  • }
  • class Grade {
  • private int grade;//The grade private element in Grade has a gradeComparator comparator
  • private String name;//The name private element in the Grade class has a nameComparator comparator
  • public int getGrade() {
  • return grade;
  • }
  • public void setGrade(int grade) {
  • this.grade = grade;
  • }
  • public String getName() {
  • return name;
  • }
  • public void setName(String name) {
  • this.name = name;
  • }
  • public Grade(int grade, String name) {//Constructor
  • this.grade = grade;
  • this.name = name;
  • }
  • public Grade(int grade) {
  • this.grade = grade;
  • }//Constructor
  • @Override
  • public String toString() {
  • return "Grade{" +
  • "grade=" + grade +
  • '}';
  • }
  • }
  • class NameComparator implements Comparator<Grade>{//Comparator
  • @Override
  • public int compare(Grade o1, Grade o2) {
  • //Rewrite the compara method, using the comparaTo method in the String class
  • return ().compareTo(());
  • }
  • }
  • class gradeComparator implements Comparator<Grade>{
  • @Override
  • public int compare(Grade o1, Grade o2) {
  • //The rewritten compara method, subtracting it to positive or negative or 0
  • return ()-();
  • }
  • }