我知道我不应该问这个问题,但我真的需要帮助为java程序开发一个小算法。 这是问题所在: 我有这种阵列:
// note that {1, 1} is present twice, is duplicated
int[][] array = {{0, 1}, {0, 2}, {1, 1}, {3, 5}, {1, 1}, {2, 2}};
我想摆脱这2个不同的阵列:
int[][] norepetition = {{0,1},{0,2},{3,5},{2,2}};
int[][] withrepetition = {{1,1}};
该函数应该将初始数组分成2个新数组,一个包含不重复的坐标,另一个包含多次坐标。
我已经考虑过使用for循环并遍历每个坐标并在检查是否已经有相同的坐标(通过再次进行for循环)之后将其复制到新的表A中...但我是寻找一种更简单/更好的方法(基础阵列非常长,我担心我的技术没有太多优化)。
谢谢!
答案 0 :(得分:0)
如果你想使用java流,你可以在下面做。
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class JavaStreams {
public static void main(String argv[])
{
Stream<Integer[]> stream = Stream.of( new Integer[][]{{0, 1}, {0, 2}, {1, 1}, {3, 5}, {1, 1}, {2, 2}});
List<Integer[]> matching = stream.filter(i -> i[0] == i[1]).collect(Collectors.toList());
Stream<Integer[]> notmatchingstream = Stream.of( new Integer[][]{{0, 1}, {0, 2}, {1, 1}, {3, 5}, {1, 1}, {2, 2}});
List<Integer[]> notmatching = notmatchingstream.filter(i -> i[0] != i[1]).collect(Collectors.toList());
System.out.println("Matching Integer arrays are: ");
matching.stream().forEach(p -> System.out.println(p[0]+", "+p[1])) ;
System.out.println("Not Matching Integer arrays are: ");
notmatching.stream().forEach(p -> System.out.println(p[0]+", "+p[1])) ;
}
}
答案 1 :(得分:-1)
import java.util.*;
public class StackQ2 {
static class IntContainer {
public IntContainer(int a, int b) {
this.a = a;
this.b = b;
}
int a;
int b;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass())
return false;
IntContainer that = (IntContainer) o;
if (a != that.a) return false;
return b == that.b;
}
@Override
public int hashCode() {
int result = a;
result = 31 * result + b;
return result;
}
@Override
public String toString() {
return "{" + a + "," + b + "}";
}
}
public static void main(String[] args) {
List<IntContainer> array = Arrays.asList(
new IntContainer(0, 1),
new IntContainer(0, 2),
new IntContainer(1, 1),
new IntContainer(3, 5),
new IntContainer(1, 1),
new IntContainer(2, 2)
);
List<IntContainer> norepetition = new ArrayList<>();
Set<IntContainer> withrepetition = new HashSet<>();
for (IntContainer element : array) {
if (Collections.frequency(array, element) > 1) {
withrepetition.add(element);
} else {
norepetition.add(element);
}
}
System.out.println("NoRep: " +Arrays.toString(norepetition.toArray()));
System.out.println("Rep: " +Arrays.toString(withrepetition.toArray()));
}
<强>输出强>:
NoRep: [{0,1}, {0,2}, {3,5}, {2,2}]
Rep: [{1,1}]