从数组中删除重复的单词并将唯一的单词返回到同一个数组

时间:2015-11-02 07:09:55

标签: java arrays

我试图从数组列表中删除重复项,我试图使用简单的for循环代替hashset ..

任何人都可以建议我如何改进我的计划:

public class removeduplicates {

    public static void main(String[] args) {
        String[] words={"Others","Others","Others","Sentence"};

        String output=words[0];
        int count=0;

        for(int i=0;i<words.length-1;i++) {
            for(int j=i+1;j<words.length;j++) {
                if(words[i].equals(words[j])) {
                    count++;
                }
                else {
                    output=output+words[j];
                }
            }
            i=count;
        }
        System.out.println(output);
    }
}

在这个程序中,如果我们提供输入为Others,Sentence,Others,Sentence,那么我没有得到所需的输出:我只需要OthersSentence作为输出......

如果可能,我有一个条件,当我输入单词数组时,我需要输出数组只有相同数组中的唯一值。

3 个答案:

答案 0 :(得分:0)

    String [] input={"other", "other","sentence","other"};

    String current=input[0];
    boolean found=false;
    for(int i=0; i<input.length; i++){
        if (current == input[i] && !found) {
            found = true;
        } else if (current != input[i]) {
            System.out.print(" " + current);
            current = input[i];
            found = false;
        }
    }

答案 1 :(得分:0)

我建议使用集合,因为你无法调整数组的大小

ArrayList<String> noDuplicateList = new ArrayList<>();
String[] words={"Others","Others","Others","Sentence"};
for(int i=0;i<words.length;i++) {
   if(!noDuplicateList.contains(words[i])){
        noDuplicateList.add(words[i]);
    }
}

这是link

答案 2 :(得分:0)

解决重复的最简单方法是使用HashSet声明,无论如何使用循环查看此代码:

第1步:将重复值替换为null

String[] words={"Others","B","Sentence","A","Others","A","Sentence"};

for(int i=0; i < words.length ;i++) {

    String toBeRemoved = words[i];

    for(int j=i+1 ; j < words.length; j++) {
        if(words[j] != null && words[j].equals(toBeRemoved)) {
            words[i] = null;
        }
    }
}

现在,如果您打印words值,则输出将为:

System.out.println(Arrays.asList(words));

输出:[null, B, null, null, Others, A, Sentence]

第2步:删除空值(有很多种方法),例如:

List<String> list = new ArrayList<>(Arrays.asList(words));
list.removeIf(new Predicate<String>() {
    @Override
    public boolean test(String t) {
        return (t == null || t.length() < 0);
    }
});
words = list.toArray(new String[0]);

使用lambda JDK 8:

words = Arrays.stream(words).filter(t -> (t != null && t.length() > 0)).toArray(String[]::new);

现在,如果您打印words值,则输出将为:

System.out.println(Arrays.asList(words));

输出:[B, Others, A, Sentence]