我想删除一个数组中的所有重复项,然后将结果写入一个空数组。
这是我目前所拥有的......
String arIndex[] = new String[rows];
String value[]; //This is my empty array
for(int i = 0; i < rows; i++) {
if (Arrays.asList(value).contains(arIndex)) {
out.println("Already Exist!");
} else {
asList[i] = value[i];
}
}
有人可以告诉我如何完成这个吗?
谢谢
最佳答案
由于您正在处理 Strings
,只要您的结果不必区分大小写,您就可以使用 HashMap 来计算出现次数。然后,当您的 HashMap 被填充时,您可以遍历它并将所有值为 1(不重复)的事件移动到数组(某种列表)。
您会在我的代码示例中看到,每个字符串都成为我的 HashMap 中的键,键的计数就是值。我不关心大小写,这就是为什么在结果中你会看到 Hello 和 hello 不被认为是重复的。如果您想考虑重复,那么您可以修改我的示例代码以忽略大小写。
public static void main(String[] args) throws Exception {
String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};
Map<String, Integer> occurrences = new HashMap<>();
// Count occurences of each string in the array
for (int i = 0; i < arIndex.length; i++) {
if (occurrences.containsKey(arIndex[i])) {
occurrences.put(arIndex[i], occurrences.get(arIndex[i]) + 1);
} else {
occurrences.put(arIndex[i], 1);
}
}
List<String> nonDuplicatesList = new ArrayList<>();
for (Map.Entry<String, Integer> occurrence : occurrences.entrySet()) {
if (occurrence.getValue() == 1) {
nonDuplicatesList.add(occurrence.getKey());
}
}
// Only do this if you're bounded to an array, otherwise just use the nonDuplicatesList
Object[] value = nonDuplicatesList.toArray();
System.out.println(Arrays.toString(value));
}
结果:
更新
在看到您的评论后,一个值为 [1, 1, 2, 3] 的数组应该导致 [1, 2, 3],下面的代码更改就是这样。
public static void main(String[] args) throws Exception {
String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};
Map<String, Integer> occurrences = new HashMap<>();
for (int i = 0; i < arIndex.length; i++) {
if (occurrences.containsKey(arIndex[i])) {
// Ignore this value cause it's a duplicate
continue;
} else {
occurrences.put(arIndex[i], 1);
}
}
arIndex = new String[occurrences.size()];
occurrences.keySet().toArray(arIndex);
System.out.println(Arrays.toString(arIndex));
}
结果:
更新
仅使用 ArrayList
的另一种方式
public static void main(String[] args) throws Exception {
String[] arIndex = new String[] {"the", "the", "1", "2", "Hello", "hello", "2"};
List<String> removedDuplicates = new ArrayList<>();
for (String arIndex1 : arIndex) {
if(!removedDuplicates.contains(arIndex1)) {
removedDuplicates.add(arIndex1);
}
}
// Setting the removedDuplicates to arIndex
arIndex = new String[removedDuplicates.size()];
removedDuplicates.toArray(arIndex);
System.out.println(Arrays.toString(arIndex));
}
结果:
关于java - 我想删除数组中的所有重复项,然后将结果写入空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29950695/