如何从ArrayList中删除重复的字符串[重复]

问题描述 投票:1回答:2

这个问题在这里已有答案:

对于赋值,我必须创建一个接收ArrayList并从中删除重复元素的方法(不区分大小写)。此外,它需要更改元素的大小写以匹配ArrayList中该String的最后一次出现的大小写。

现在我正在尝试一个3步骤的过程:创建一个新的字符串ArrayList并用与输入元素相同的元素填充它。然后我使用嵌套的for循环来迭代它,将元素的重复更改为“REMOVE_THIS_STRING”,并更改每个String的第一个实例以匹配最后一个实例的大小写。然后,在另一个循环中,我遍历并删除与“REMOVE_THIS_STRING”字符串匹配的所有元素。我知道这不是最有效的方法,但是我没有对其他类型的集合做太多工作,所以我现在犹豫是否要捣乱那些并且更喜欢只使用ArrayLists的方法,如果可能。

/*
Code that creates the NewArrayList ArrayList and fills it 
with elements identical to that of the input ArrayList
*/



for(int i=0; i<input.size(); ++i) {
   String currentWord = input.get(i);
   for(int j=i+1; j<input.size(); ++j) {
      String wordToCompare = input.get(j);

      if(currentWord.equalsIgnoreCase(wordToCompare)) {
         currentWord = wordToCompare;
         newArrayList.set(i, wordToCompare);
         newArrayList.set(j, "REMOVE_THIS_STRING");
      }
   }
}



/*
Code that goes through NewArrayList and removes 
all Strings set to "REMOVE_THIS_STRING"
*/

如果ArrayList输入是"interface", "list", "Primitive", "class", "primitive", "List", "Interface", "lIst", "Primitive",预期输出是"Interface", "lIst", "Primitive", "class",而是我得到"Interface", "lIst", "Primitive", "class", "Primitive", "lIst"

java arraylist
2个回答
1
投票

要删除重复项,您可以使用Java 8 stream.distict()像这样:

List<Integer> newArrayList= input.stream()
     .map(String::toLowerCase)
     .distinct()
     .collect(Collectors.toList());
}

它区分大小写,因此您必须先映射到小写。

要将每个结果的第一个字母大写不同的单词,您需要添加:

.map(name -> name.substring(0, 1).toUpperCase() + name.substring(1))

在流处理中。所以它将是:

List<Integer> newArrayList= input.stream()
     .map(String::toLowerCase)
     .distinct()
     .map(word-> word.substring(0, 1).toUpperCase() + word.substring(1))
     .collect(Collectors.toList());
}

1
投票

这会更改保留值的相对顺序,但不会将其作为要求提供。

  List<String> input = new ArrayList<>(List.of("interface",
        "list",
        "Primitive",
        "class",
        "primitive",
        "List",
        "Interface",
        "lIst",
        "Primitive"));

  for (int k = 0; k < input.size(); k++) {
     String word = input.get(k);
     // remove them all
     for (int i = 0; i < input.size(); i++) {
        if (input.get(i).equalsIgnoreCase(word)) {
           word = input.remove(i);
        }
     }

     //add in the last one removed.
     input.add(0, word);
  }

  System.out.println(input);
© www.soinside.com 2019 - 2024. All rights reserved.