java - 对数组进行排序并找到重复的数字
问题描述
package array;
import java.util.Arrays;
public class learning_program1 {
public static void main(String[] args) {
int arr[]= {1,2,3,4,10,20,30,6,6,5,4,5,5,2};
Arrays.sort(arr);
for(int i = 0; i < arr.length; i++)
{
int count =0;
int flag=0;
for(int j=i+1; j<arr.length; j++)
{
while(arr[i] == arr[j])
{
count++;
j++;
flag=1;
}
break;
}
if(flag==1)
{
System.out.println("the repeated values " + arr[i] + " is " +count);
}
}
}
}
输出:
重复值 2 为 1
重复值 4 为 1
重复值 5 为 2
重复值 5 为 1
重复值 6 为 1
我的问题是我得到了输出,但是 5 重复了两次
解决方案
您可以使用Stream
. 首先,您必须按其值对给定中的所有元素进行分组arr
并计算它们。然后,过滤出现多次的元素。
public static Map<Integer, Integer> findDuplicates(int[] arr) {
Map<Integer, Long> map = Arrays.stream(arr)
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
Map<Integer, Integer> res = new TreeMap<>();
map.entrySet().stream()
.filter(entry -> entry.getValue() > 1)
.forEach(entry -> res.put(entry.getKey(), entry.getValue().intValue() - 1));
return res;
}
在这种情况下,您的客户端代码将如下所示:
int arr[] = { 1, 2, 3, 4, 10, 20, 30, 6, 6, 5, 4, 5, 5, 2 };
Map<Integer, Integer> map = findDuplicates(arr);
map.forEach((key, count) -> System.out.println("the repeated values " + key + " is " + count));
输出:
the repeated values 2 is 1
the repeated values 4 is 1
the repeated values 5 is 2
the repeated values 6 is 1
PS
如果您犹豫使用Stream
,没有它很容易做到,只需依靠Set
and Map
:
public static Map<Integer, Integer> findDuplicates(int[] arr) {
Set<Integer> values = new HashSet<>();
Map<Integer, Integer> map = new TreeMap<>();
for (int val : arr)
if (!values.add(val))
map.put(val, map.getOrDefault(val, 0) + 1);
return map;
}
推荐阅读
- swiftui - SwiftUI:在带有动画的计时器上更改图像
- python - pandas multiindex DataFrame中的圆形浮点数
- reactjs - 在反应中使用 URLSearchParams 获取 url 参数
- django - 无法将链接 postgreSQL 加载到 Django
- javascript - 在不使用 Websocket 的情况下使用 RTP 流式传输音频
- wcf - 配置 netTcpBinding
- java - 如何正确使用 AsyncTask?
- c# - 使用“Web Controller 2 with actions, using Entity Framework”加入咨询
- python - 如何为准确性创建自定义张量流指标
- node.js - 通知用户(客户端应用程序)服务器端应用程序正在处理他们上传的文件的最佳实践是什么。反应、节点和 MongoDB