public class Pascal {
public static void main(String[] args){
int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (i == j){
System.out.println(i);
} else {
System.out.println("Nothing");
}
}
}
}
}
它不能正常工作。我尝试使用foreach
循环,但效果不佳。我认为这差不多完成了,我错过了一些微不足道的事情。
你的问题
i
而不是array[i]
。这将起作用,但仍会打印几次重复值:
int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13,13};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] == array[j] && i != j){
System.out.println(array[i]);
}
}
}
现在,我向您展示解决此问题的不同样式。
命令式风格的更好解决方案。
您正在解析n
无用的数组时间。只要数组已排序(您仍然可以对其进行排序),就可以像下面的解决方案一样将元素与下一个元素进行比较:
int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};
//Optionally
Arrays.sort(array);
Integer last = null;
for(int i = 0; i < array.length -1 ; i++) {
if(array[i] == array[i+1] && (last == null || !last.equals(array[i]))) {
System.out.println(array[i]);
last = array[i];
}
}
我认为这是最有效的解决方案,但不是最易读的。
带有foreach循环的另一种解决方案
除非您明确需要访问当前元素的索引,否则使用普通的旧for
循环是有害的,因为它引入了不必要的变量i
,从而污染了代码的可读性。
您可以首选使用foreach语句:
int array[] = {1,2,3,3,3,4,5,6,6,7,8,8,10,10,11,12,13,13};
Set<Integer> uniqueValues = new HashSet<>();
Set<Integer> alreadyDisplayed = new HashSet<>();
for(Integer value : array) {
if(uniqueValues.contains(value) && !alreadyDisplayed.contains(value)) {
System.out.println(value);
alreadyDisplayed.add(value);
}
uniqueValues.add(value);
}
功能样式的更好解决方案。
此解决方案对Java8更友好:
int array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};
//Count occurrences of each number
Map<Integer, Integer> map = new HashMap<>();
Arrays.stream(array).forEach(value -> {
Integer occurrences = map.get(value);
map.put(value, occurrences == null ? 1 : occurrences +1);
});
//Display number of occurrences when nbOccurrences > 1
map.entrySet()
.stream()
.filter(entry -> entry.getValue() > 1)
.forEach(entry -> System.out.println(entry.getKey() + " : "+entry.getValue()));
注意,它还给出每个值的出现次数。如果不需要它们,可以像以前的解决方案一样缩短代码。
逻辑风格的有趣解决方案。
Integer array[] = {1,2,3,3,4,5,6,6,7,8,8,10,10,11,12,13};
//Convert the array to a list.
List<Integer> list = Arrays.stream(array).collect(Collectors.toList());
//Use a Set in order to build the collection of unique values.
Set<Integer> uniqueValues = new HashSet<>(list);
//Remove each unique value once from the original list.
uniqueValues.stream().forEach(list::remove);
//Re-compute unique values of the resulting list and display them.
new HashSet<>(list).forEach(System.out::println);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句