1.将数组保存到List中,并按倒序、从大到小的顺序显示出来
@Test
public void listTest() {
List list = new ArrayList();
int[] arr = {1, 2, 3, 4, 8, 7, 6, 5};
for (int i = 0; i < arr.length; i++) {
list.add(arr[i]);
}
Collections.sort(list);
Collections.reverse(list);
System.out.println("排序后的顺序:");
Iterator iterator = list.iterator();
while (iterator.hasNext()) {
System.out.print(iterator.next() + " ");
}
}
2.请把学生名与考试分数录入到集合中,并按分数显示前三名成绩学员的名字。
@Test
public void treeSetTest(){
HashMap<String, Integer> student = new HashMap<>();
student.put("AA",80);
student.put("BB",90);
student.put("CC",70);
student.put("DD",100);
Set<Map.Entry<String, Integer>> entries = student.entrySet();
ArrayList<Map.Entry<String, Integer>> entries1 = new ArrayList<>(entries);
Collections.sort(entries1, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue() - o1.getValue();
}
});
for (int i = 0; i < 3; i++) {
System.out.println(entries1.get(i));
}
}