用面向对象的方法求出给定数组中重复 value 的个数。

用面向对象的方法求出数组中重复 value 的个数。


int[] arr = {1,8,2,2,8,8,3,2,2,3}; 
按如下个数,格式输出:
1 出现:13 出现:28 出现:32 出现:4import java.util.TreeMap;

public class Main {
	public static void main(String[] args) {
		int[] arr = { 1, 8, 2, 2, 8, 9, 8, 0, 6, 8, 7, 4, 5, 8, 3, 2, 2, 3 };
		calculate(arr);
	}

	public static void calculate(int[] arr) {
		TreeMap<Integer, Integer> map = new TreeMap<Integer, Integer>();
		for (int i = 0; i < arr.length; i++) {
			if (map.containsKey(arr[i])) {
				map.put(arr[i], map.get(arr[i]) + 1);
			} else {
				map.put(arr[i], 1);
			}
		}
		System.out.println("统计后,输出前:");
		System.out.println(map);
		int n = map.size();
		for (int i = 0; i < n; i++) {
			System.out.println(map.firstKey() + "出现:" + map.get(map.firstKey()) + "次");
			map.remove(map.firstKey());
		}
		System.out.println("输出后(由于map不能根据index下标索引来获取元素,只能一个一个获取第
		一个键值对,然后删除来实现,所以最终为空的):");
		System.out.println(map);
	}
}

运行结果如下所示:

在这里插入图片描述

发布了32 篇原创文章 · 获赞 1 · 访问量 2820

猜你喜欢

转载自blog.csdn.net/YOUAREHANDSOME/article/details/105068797
今日推荐