import java.util.Arrays;
public class ClassNameHere {
public static void main(String[] args) {
String[] items = new String[]{"John","Bob","David", "Carrie", "John","Bob","Dawson"};
String [] clone = new String[items.length];
for (int i =0; i<items.length; i++) {
clone[i] = items[i]; // copying the items array to clone
}
for (int i=items.length-1; i>=0; i--) { //trying to find duplicates.
for (int j = i-1; j>=0; j--) {
if (items[i].equals(items[j])) {
}
}
}
嗨,我目前正在处理我的数组以删除所有重复项并将其更改为空值并将所有空值移动到右侧。因此,例如,由于存在“John”和“Bob”重复项,这就是我期望的结果:{“David”、“Carrie”、“John”、“Bob”、“Dawson”、null、null} .此外,您将看到我正在制作项目的克隆数组,因为我不想更改原始项目的任何值。
最佳答案
尝试这个。
String[] items = new String[] {"John", "Bob", "David", "Carrie", "John", "Bob", "Dawson"};
String[] clone = Arrays.copyOf(Arrays.stream(items)
.distinct().toArray(String[]::new), items.length);
System.out.println(Arrays.toString(clone));
输出:[John, Bob, David, Carrie, Dawson, null, null]
如果您不想使用 Stream
String[] items = new String[] {"John", "Bob", null, "David", "Carrie", "John", "Bob", "Dawson"};
int length = items.length;
String[] clone = new String[length];
L: for (int i = 0, last = 0; i < length; ++i) {
String item = items[i];
if (item == null) continue;
for (int j = 0; j < last; ++j)
if (item.equals(clone[j]))
continue L;
clone[last++] = items[i];
}
System.out.println(Arrays.toString(clone));
输出:[John, Bob, David, Carrie, Dawson, null, null, null]
关于java - 替换数组中的所有重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68141903/