java - 比较并从java中的2个数组中提取相似的字符串,不重复

标签 java arrays duplicates

我正在尝试从 2 个数组中提取相似的字符串,并且我已经成功地做到了,只是它们在重复。即 array 1 {"arrow", "arrow", "sycophant"}array 2 ("arrow", "sycophant", "bulbasaur"} 会给我{"arrow", "arrow","sycophant"} 的输出,而我只想获得一次箭头。有什么建议吗?

public static void main(String[] args) {
    String[] words1 = { "sycophant", "rattle", "zinc", "alloy", "tunnel", "arrow" };
    String[] words2 = { "sycophant", "arrow", "arrow" };

    // String prefix = "a";
    // String substring = "at";
    // char[] letters = { 'a', 'b' };

    // String[] output = wordsStartingWith(words1, prefix);
    // String[] output = wordsContainingPhrase(words1, substring);
    // String[] output = wordsContainingAll(words1, letters);
    String[] output = wordsInBoth(words1, words2);

    for (int i = 0; i < output.length; i++) {
        System.out.println("Words: " + i + " " + output[i]);
    }
}

public static String[] wordsInBoth(String[] words1, String[] words2) {
    // method that finds and returns common words in two arrays
    String[] returnWords;
    int countWords = 0;

    for (int i = 0; i < words1.length; i++) {
        for (int j = 0; j < words2.length; j++) {
            if (words1[i].equalsIgnoreCase(words2[j])) {
                countWords++;
            }
        }
    }

    returnWords = new String[countWords];
    countWords = 0;

    for (int i = 0; i < words1.length; i++) {
        for (int j = 0; j < words2.length; j++) {
            if (words1[i].equalsIgnoreCase(words2[j]) 
                    && !words1[i].equalsIgnoreCase(returnWords[countWords])) {
                returnWords[countWords] = words1[i];
                countWords++;
            }
        }
    }

    return returnWords;
}

最佳答案

一种可能性是存储在 HashSet 中找到的单词,这不会添加重复项。

// method that finds and returns common words in two arrays
public static String[] wordsInBoth(String[] words1, String[] words2) { 

    Set<String> returnWords = new HashSet<String>();

    for (int i = 0; i < words1.length; i++) {
        for (int j = 0; j < words2.length; j++) {
            if (words1[i].equalsIgnoreCase(words2[j]))
                returnWords.add(words1[i]);
        }
    }

    return returnWords.toArray(new String[returnWords.size()]);
}

关于java - 比较并从java中的2个数组中提取相似的字符串,不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35190047/

相关文章:

python - 如何在 python 中使用 pandas 获取所有重复项的列表?

java - Webmethods - 它可以托管自己的 Web 服务吗?

java - if - else if 条件检查BUG

Java 代码效率,存储数据与方法调用

java - 如何在java中将Time转换为int

r - 同时删除两列中的重复行

java - Dataflow JAVA SDK : Take the code as an input, 后台进程

javascript - 从数组中删除单个项目或数组的函数 - javascript

java - 从MySQL读取数据到eclipse中

javascript - 如何将索引为 0 的重复数组合并为一个数组 javascript