- 题目
编写程序解决以下问题:长度为 N 的数组,随机放入值为 1-50 中间的任意 整数,请编写程序找出其中的偶数数字,并按照该数字在数组中出现次数从多到少排序 输出。
- 分析
首先建立长度为n的数组,通过Random r = new Random(); r.nextInt(50) + 1 实现随机数生成然后放入数组中。题目要求找偶数 那就是生成数字和2 取余 ,等于0 那就是偶数了,把偶数做为key单独放一个Map数组,出现的次数 作为Value. 统计Map数组key次数做 (evenMap.merge(temp, 0,Integer::sum); 这个是计算相同key 累加value)。最后对value 做从大到小排序,使用Java8特性sorted(Comparator.comparing(Map.Entry<Integer, Integer>::getValue).reversed())// 从大到小
具体代码如下: - 代码实现
package com.dairuijie.demo.study;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;
import java.util.stream.Collectors;
/**
*
* @模块名:Day01
* @包名:com.dairuijie.demo.study
* @描述:FindEven.java
* @版本:1.0
* @创建人:drj
* @创建时间:2020年3月28日下午5:18:52
*/
public class FindEven {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
System.out.print("请输入整数n:");
Integer read = Integer.valueOf(scan.nextLine());
ArrayList<Integer> list = new ArrayList<>();
Map<Integer,Integer> evenMap = new HashMap<Integer,Integer>();
Random r = new Random();
for(int i=0; i < read; i++) {
Integer temp = r.nextInt(50) + 1;
list.add(temp);
if(temp%2 ==0) {
evenMap.merge(temp, 0,Integer::sum);
}
}
System.out.println("初始化数组:" + list);
List<Integer> sortMapByValue = sortMapByValue(evenMap);
System.err.println("偶数排序数组:" + sortMapByValue);
scan.close();
}
/**
* //map集合根据value从大到小排序
* @方法名:sortMapByValue
* @方法描述:
* @param map
* @return
* @修改描述:
* @版本:1.0
* @创建人:drj
* @创建时间:2020年3月28日 下午5:37:58
* @修改人:drj
* @修改时间:2020年3月28日 下午5:37:58
*/
public static List<Integer> sortMapByValue(Map<Integer, Integer> map) {
int size = map.size();
List<Map.Entry<Integer, Integer>> list = new ArrayList<Map.Entry<Integer, Integer>>(size);
list.addAll(map.entrySet());
List<Integer> keys = list.stream()
.sorted(Comparator.comparing(Map.Entry<Integer, Integer>::getValue).reversed())// 从大到小
.map(Map.Entry<Integer, Integer>::getKey)
.collect(Collectors.toList());
return keys;
}
}
- 运行效果
请输入整数n:50
初始化数组:[19, 32, 25, 48, 1, 6, 32, 18, 42, 23, 7, 34, 45, 42, 26, 11, 5, 5, 12, 14, 48, 38, 24, 15, 37, 20, 18, 50, 25, 17, 34, 27, 34, 7, 20, 37, 9, 10, 24, 33, 42, 4, 48, 31, 21, 47, 30, 24, 20, 50]
偶数排序数组:[32, 34, 4, 38, 6, 10, 42, 12, 14, 48, 50, 18, 20, 24, 26, 30]