English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

A Collection Framework Question in Java: Multiple Solution Approaches

Question:A class30, the student number of the student is20070301-20070330, all students have taken the Java Programming Design course, and all students' grades are given (random numbers can be generated, ranging60-100), please write a program to sort and print the grades of all students in this class from low to high.

Requirements:Implement with List, Map, and Set respectively, the printed information includes student number, name, and grade.

1Using the List collection to implement

import java.util.ArrayList; 
import java.util.Collections; 
import java.util.Comparator; 
import java.util.Iterator; 
import java.util.LinkedList; 
import java.util.TreeMap; 
public class Test2{ 
  public static void main(String[] args){ 
    /* Here ArrayList is used 
     * 
     * ArrayList<Student>al=new ArrayList<Student>(); 
    for(int i=20070301,j=10;i<=20070330;i++,j++) 
    { 
      al.add(new Student(i,(int) (40*Math.random()+60), "Student"+j)); 
    } 
    //ArrayList sorting is implemented using the sort() method in Collections. 
    Collections.sort(al, new Sortbygrade()); 
    for(Student sd:al) 
    System.out.println(sd); 
    */ 
    LinkedList<Student> lt=new LinkedList<Student>(); 
    for(int i=20070301,j=10;i<=20070330;i++,j++) 
    { 
      lt.add(new Student(i,(int) (40*Math.random()+60), "Student"+j)); 
    } 
    //Sort the linked list 
    Collections.sort(lt, new Sortbygrade()); 
    //Output the linked list 
    for(Student sd:lt) 
      System.out.println(sd); 
  } 
} 
//Student class 
class Student{ 
  int num,grade; 
  String name; 
  //Constructor 
  public Student(int num,int grade,String name){ 
    this.num=num; 
    this.name=name; 
    this.grade=grade; 
  } 
  //Here it is necessary to override 
  public String toString(){ 
//   System.out.println("hi"); 
    return "Student ID:"+this.num+"\t"+"Name:"+this.name+"  "+"成绩:"+this.grade; 
  } 
} 
//Create a comparator class 
class Sortbygrade implements Comparator<Student>{ 
  @Override 
  public int compare(Student s1, Student s2) { 
    if(s1.grade>s2.grade) 
      return 1; 
    if(s1.grade<s2.grade) 
      return -1; 
    if(s1.grade==s2.grade) 
      return s1.name.compareTo(s2.name); 
    return 0;     
  } 
} 

 The output result is shown in the figure:

On the List collection framework'sSummary:

1In fact, the List collection is a dynamic array, elements can be directly retrieved through a for loop without iteration.
2, when outputting a List collection, the default method called is the toString() method of the objects stored in the collection, so it needs to be overridden in the class.
If the toString() method is not overridden, it must be used

for(int i=0;i<lt.size();i++) 
{ 
  Student s=lt.get(i); 
  System.out.println("学号:"+s.num+"  Name:",+s.name+"  Score:",+s.grade); 
} 

3, sorting of List collection requires the use of the Collections utility class, i.e., Collections.Sort(list, new Comparator class()) method. Therefore, a custom comparator class needs to be defined, defining your own comparison rules.

2, to implement using Set collection
(1to implement using TreeSet

package com.package1; 
import java.util.*; 
public class StuScore { 
public static void main(String[] args) { 
  TreeSet<Student> ts=new TreeSet<Student>(new Com()); 
  //Add elements into 
  for(int i=20070301,j=1;i<=20070330;i++,j++) 
  { 
    ts.add(new Student(i,"Student"+j,(int) (40*Math.random()+60))); 
  } 
  //Iteratively loop to extract 
  Iterator<Student> it=ts.iterator(); 
  while(it.hasNext()) 
  { 
    Student o1=it.next(); 
    System.out.println("学号:"+o1.num+" ",+"姓名:"+o1.name+" ",+" ",+"Score:",+o1.grade); 
  } 
} 
} 
//Student class 
class Student  
{ 
int num; 
int grade; 
String name; 
public Student(int num, String name, int grade) 
{ 
  this.num=num; 
  this.name=name; 
  this.grade=grade; 
} 
} 
class Com implements Comparator 
{ 
@Override 
public int compare(Object o1, Object o2) { 
  Student s1=(Student) o1; 
  Student s2=(Student) o2; 
  if(s1.grade>s2.grade) 
    return 1; 
  if(s1.grade<s2.grade) 
    return -1; 
  if(s1.grade==s2.grade) 
  { 
    return new Integer(s1.num).compareTo(new Integer(s2.num)); 
  } 
  return 0; 
} 
} 

The output result is:

Student ID:20070307  Name: Student16    Score:60
Student ID:20070309  Name: Student18    Score:60
Student ID:20070314  Name: Student23    Score:61
Student ID:20070318  Name: Student27    Score:61
Student ID:20070322  Name: Student31    Score:61
Student ID:20070306  Name: Student15    Score:62
Student ID:20070310  Name: Student19    Score:64
Student ID:20070302  Name: Student11    Score:66
Student ID:20070308  Name: Student17    Score:68
Student ID:20070321  Name: Student30  Score:68
Student ID:20070330  Name: Student39    Score:69
Student ID:20070303  Name: Student12    Score:70
Student ID:20070320  Name: Student29    Score:70
Student ID:20070323  Name: Student32    Score:77
Student ID:20070313  Name: Student22    Score:78
Student ID:20070304  Name: Student13    Score:79
Student ID:20070324  Name: Student33    Score:83
Student ID:20070326  Name: Student35    Score:84
Student ID:20070327  Name: Student36    Score:85
Student ID:20070311  Name: Student20  Score:88
Student ID:20070305  Name: Student14    Score:89
Student ID:20070329  Name: Student38    Score:89
Student ID:20070316  Name: Student25    Score:90
Student ID:20070301  Name: Student10    Score:95
Student ID:20070312  Name: Student21    Score:96
Student ID:20070317  Name: Student26    Score:97
Student ID:20070319  Name: Student28    Score:97
Student ID:20070325  Name: Student34    Score:98
Student ID:20070315  Name: Student24    Score:99
Student ID:20070328  Name: Student37    Score:99

forTreeSetSummary:
1, elements cannot be repeated, and TreeSet is ordered.
2, two sorting methods:
(1Customize a comparator class, for example class Com implements Comparator{ }, and implement compare(Object o1, Object o2method, where the comparison rules are defined.
(2to make the elements themselves comparable.
Steps: Implement the Comparable interface for the elements added to the TreeSet and override the compareTo method. This order is also the natural order of the elements, or what is called the default order.

method1and method2The difference is:

Both methods have their advantages and disadvantages. Using Comparable is simple, as objects that implement the Comparable interface become directly comparable without the need to modify the source code.

The advantage of using Comparator is that you do not need to modify the source code. Instead, you implement another comparator. When a custom object needs to be compared, you can pass the comparator and the object together to compare sizes. And in the Comparator, users can implement complex and general logic themselves, so that it can match some simple objects, which can save a lot of repetitive work.

(2)usingHashSetto implement

package com.package1; 
import java.util.*; 
public class StuScore { 
  public static void main(String[] args) { 
    HashSet<Student> hs=new HashSet<Student>(); 
    //Add elements into 
    for(int i=20070301,j=1;i<=20070330;i++,j++) 
    { 
      hs.add(new Student(i,"Classmate"+j,(int)  
(40*Math.random()+60))); 
    } 
    ArrayList<Student>li=new ArrayList(hs); 
    Collections.sort(li, new Sortbygrade()); 
    for(Student ss:li) 
      System.out.println(ss); 
  } 
} 
//Student class 
class Student  
{ 
  int num; 
  int grade; 
  String name; 
  public Student(int num, String name, int grade) 
  { 
    this.num=num; 
    this.name=name; 
    this.grade=grade; 
  } 
  public String toString(){ 
    //System.out.println("hi"); 
    return "Student ID:"+this.num+"\t"+"Name:"+this.name 
+"  "+"成绩:"+this.grade; 
  } 
} 
class Sortbygrade implements Comparator{ 
  @Override 
  public int compare(Object o1, Object o2) { 
    Student s1=(Student) o1; 
    Student s2=(Student) o2; 
    if(s1.grade>s2.grade) 
      return 1; 
    if(s1.grade<s2.grade) 
      return -1; 
//   if(s1.grade==s2.grade) 
    return 0; 
  } 
} 

The output result is as follows:
Student ID:20070310 Name: Classmate19    Score:60
Student ID:20070330 Name: Classmate39    Score:62
Student ID:20070326 Name: Classmate35    Score:63
Student ID:20070317 Name: Classmate26    Score:64
Student ID:20070318 Name: Classmate27    Score:65
Student ID:20070322 Name: Classmate31    Score:65
Student ID:20070301 Name: Classmate10    Score:67
Student ID:20070328 Name: Classmate37    Score:68
Student ID:20070304 Name: Classmate13    Score:68
Student ID:20070319 Name: Classmate28    Score:69
Student ID:20070313 Name: Classmate22    Score:70
Student ID:20070303 Name: Classmate12    Score:71
Student ID:20070312 Name: Classmate21    Score:71
Student ID:20070329 Name: Classmate38    Score:72
Student ID:20070306 Name: Classmate15    Score:72
Student ID:20070324 Name: Classmate33    Score:72
Student ID:20070305 Name: Classmate14    Score:75
Student ID:20070315 Name: Classmate24    Score:75
Student ID:20070314 Name: Classmate23    Score:78
Student ID:20070307 Name: Classmate16    Score:80
Student ID:20070311 Name: Classmate20 Score:81
Student ID:20070302 Name: Classmate11    Score:83
Student ID:20070309 Name: Classmate18    Score:84
Student ID:20070320 Name: Classmate29    Score:85
Student ID:20070321 Name: Classmate30 Score:85
Student ID:20070316 Name: Classmate25    Score:86
Student ID:20070327 Name: Classmate36    Score:90
Student ID:20070308 Name: Classmate17    Score:94
Student ID:20070323 Name: Classmate32    Score:94
Student ID:20070325 Name: Classmate34    Score:95

forHashSetSummary:
1Elements in HashSet cannot be duplicated. If a duplicate is added, only one will be displayed.
The principle is as follows:
HashSet: The underlying data structure is a hash table. It is not thread-safe and is not synchronized.
2How does HashSet ensure the uniqueness of elements?
答:是通过元素的两个方法,hashCode和equals来完成。
如果元素的HashCode值相同,才会判断equals是否为true。如果元素的hashcode值不同,不会调用equals。
3、对HashSet的排序,通过将Set集合转换为List集合,借助Collections.sort()方法实现排序。

3、使用TreeMap来实现

package com.package1;  
import java.util.Comparator; 
import java.util.Iterator; 
import java.util.Set; 
import java.util.TreeMap; 
public class TestTreeMap { 
  public static void main(String[] args) { 
    //1.创建集合 
    TreeMap<Student, Integer> tm = new TreeMap<Student, Integer>(); 
    for(int i=20070301,j=10;i<=20070330;i++,j++) 
    { 
      int grade = (int) (40*Math.random()+60); 
       //2、向集合对象中添加元素 
       tm.put(new Student(grade,"同学"+j),i); 
    } 
    //3.遍历集合,排序完成  
    Set<Student> k = tm.keySet(); 
    Iterator<Student> it = k.iterator(); 
    while(it.hasNext()){ 
      Student key = it.next(); 
      Integer num = tm.get(key); 
      System.out.println("学号:"+num+"  "+"姓名:"+key.name+"  "+"成绩:"+key.grade); 
    } 
  } 
} 
class Student implements Comparable<Student> { 
  int grade; 
  String name; 
  public Student(int grade, String name) { 
    this.grade = grade; 
    this.name=name; 
  } 
  @Override 
  public int compareTo(Student o) { 
    if(this.grade>o.grade)  
      return 1;  
      if(this.grade==o.grade)  
      { //Sort by name when the scores are the same 
       return this.name.compareTo(o.name);  
      }  
      return -1;  
  } 
} 

 The output result is:

Student ID:20070303    Name: Student12    Score:61
Student ID:20070323    Name: Student32    Score:61
Student ID:20070317    Name: Student26    Score:62
Student ID:20070309    Name: Student18    Score:64
Student ID:20070301    Name: Student10    Score:67
Student ID:20070304    Name: Student13    Score:69
Student ID:20070322    Name: Student31    Score:69
Student ID:20070328    Name: Student37    Score:70
Student ID:20070305    Name: Student14    Score:71
Student ID:20070319    Name: Student28    Score:73
Student ID:20070321    Name: Student30 Score:74
Student ID:20070310    Name: Student19    Score:81
Student ID:20070315    Name: Student24    Score:82
Student ID:20070307    Name: Student16    Score:84
Student ID:20070330 Name: Student39    Score:84
Student ID:20070312    Name: Student21    Score:85
Student ID:20070324    Name: Student33    Score:87
Student ID:20070306    Name: Student15    Score:88
Student ID:20070308    Name: Student17    Score:90
Student ID:20070327    Name: Student36    Score:90
Student ID:20070318    Name: Student27    Score:91
Student ID:20070316    Name: Student25    Score:92
Student ID:20070320 Name: Student29    Score:92
Student ID:20070314    Name: Student23    Score:93
Student ID:20070313    Name: Student22    Score:94
Student ID:20070302    Name: Student11    Score:95
Student ID:20070325    Name: Student34    Score:95
Student ID:20070329    Name: Student38    Score:97
Student ID:20070326    Name: Student35    Score:98
Student ID:20070311    Name: Student20 Score:99

forTreeMapSummary:
1The TreeMap default sorts the key, so you can put a custom object into the key, and put the integer representing the student number into the value. When sorting the key, you can specify a certain attribute of the custom object to sort.
2The Map collection uses the put() method to add elements.
3The principle of extracting from the Map collection: convert the map collection into a set collection and then retrieve it through the iterator. The two ways to retrieve the map collection are:
(1Set<k> keySet:Store all the keys in the map into the Set collection. Because the set has an iterator, all keys can be retrieved in an iterative manner, and the value corresponding to each key can be obtained by the get method.
(2Set<Map.Entry<k,v>> entrySet:The mapping relationship in the map collection is stored in the set collection, and the data type of this relationship is: Map.Entry

That's all for this article. I hope it will be helpful to everyone's learning, and I also hope everyone will support the Shouting Tutorial more.

Declaration: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal responsibility. If you find any content suspected of copyright infringement, please send an email to: notice#oldtoolbag.com (Please replace # with @ when sending an email to report, and provide relevant evidence. Once verified, this site will immediately delete the content suspected of infringement.)

You May Also Like