一、题目
1.原题
给定一个乱序的数组,
删除所有的重复元素,使得每个元素只出现一次,(hashMap)
并且按照出现的次数从高到低进行排序,(compartor)
相同出现次数按照第一次出现顺序进行先后排序。
二、思路与代码过程
1.思路
①统计次数:hashMap的containsKey(num),若有则put(num,countMap.get(num)+1)计数加一;若无则加入,计数为1;
②排序:ArrayList的list.sort(Comparator.comparingInt(a -> a[1]))。
2.代码过程
import java.util.*;
public class test28 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个乱序的数组:");
String s = sc.nextLine();
String[] a = s.split(" ");
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
Map<Integer,Integer> countMap = new HashMap<>();
for (int num : b) {
if (countMap.containsKey(num)) {
countMap.put(num, countMap.get(num) + 1);
}else {
countMap.put(num, 1);
}
}
//用ArrayList转存统计好次数的数据
ArrayList<int[]> list = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
list.add(new int[]{entry.getKey(), entry.getValue()});
}
//用sort方法根据出现次数进行从小到大的排序
list.sort(Comparator.comparingInt(a -> a[1]));
//要求次数从高到低排序
//用Collections.reverse 方法来反转
Collections.reverse(list);
int[] ReHX = new int[list.size()];
for (int i = 0; i <list.size(); i++) {
ReHX[i] = list.get(i)[0];
}
//存取list的第一个元素进行输出
System.out.println("该数组按出现次数从高到低排序的结果为:"+Arrays.toString(ReHX));
}
}
三、运行结果
1.运行截图
2.带数据分析运行结果
0 : 6
1 : 2
2 : 2
3 : 2
6 : 1
7 : 1
9 : 2
0 6
1 2
2 2
3 2
6 1
7 1
9 2
6 1
7 1
1 2
2 2
3 2
9 2
0 6
该数组按出现次数从高到低排序的结果为:[0, 9, 3, 2, 1, 7, 6]
3.带数据分析完整代码
import java.util.*;
public class test28 {
public static void main(String[] args) {
/*
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个乱序的数组:");
String s = sc.nextLine();
String[] a = s.split(" ");
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
System.out.println(Arrays.toString(b));
*/
int[] hx = {1,9,9,7,0,3,0,6,2,0,0,2,1,0,3,0};
//用hashMap对数字出现的次数进行统计
Map<Integer,Integer> countMap = new HashMap<>();
for (int num : hx) {
if (countMap.containsKey(num)) {
countMap.put(num, countMap.get(num) + 1);
}else {
countMap.put(num, 1);
}
}
//用ArrayList转存统计好次数的数据
ArrayList<int[]> list = new ArrayList<>();
for (Map.Entry<Integer, Integer> entry : countMap.entrySet()) {
list.add(new int[]{entry.getKey(), entry.getValue()});
System.out.println(entry.getKey() + " : " + entry.getValue());
}
System.out.println();
///*
for (int[] arr : list) {
System.out.println(arr[0] + " " + arr[1]);
}
System.out.println();
//*/
//用sort方法根据出现次数进行从小到大的排序
list.sort(Comparator.comparingInt(a -> a[1]));
///*
for (int[] arr : list) {
System.out.println(arr[0] + " " + arr[1]);
}
System.out.println();
//*/
//要求次数从高到低排序
//用Collections.reverse 方法来反转
Collections.reverse(list);
//
int[] ReHX = new int[list.size()];
for (int i = 0; i <list.size(); i++) {
ReHX[i] = list.get(i)[0];
}
//存取list的第一个元素进行输出
System.out.println("该数组按出现次数从高到低排序的结果为:"+Arrays.toString(ReHX));
}
}