将 ArrayList 元素移动到 List 中的最后一个位置?

jav*_*999 2 java arraylist

在下面的方法我有一个ArrayList的Strings。

我检查这些字符串中是否有任何一个在 txt 文件(checkIfWordIsInTextFile方法)中。

如果一个字符串在这个列表中,我想把它放在列表的最后,然后返回重新排序的列表。

我正在尝试使用 set 方法,但我不确定如何将字符串设置为列表中的最后一个元素。

当前方法:

 public List<String> placeParentsLastInLineItemList(List<String> listToReorder){

    for(String string: listToReorder){

       if(checkIfWordIsInTextFile(string)==true){
          listToReorder.set(,string); //how to set the string to the last element in list?
       }

    return listToReorder;
 }
Run Code Online (Sandbox Code Playgroud)

Ros*_*rew 5

最简单的解决方案(适合初学者)

该ArrayList中和列表默认的add()定义的行为,增加了列表的末尾。所以:-

listToReorder.add(string)
Run Code Online (Sandbox Code Playgroud)

不过,您需要将其从其原始位置移除,所以不要使用 for-each 循环,使用索引,然后当您找到它时:-

listToReorder.remove(i);
Run Code Online (Sandbox Code Playgroud)

...在将其重新添加到最后之前,因此:-

for (int i=0; i<listToReorder.size(); i++){
  String item = listToReorder.get(i);

//NOTE: '==true' isn't required if the method returns a boolean
  if(checkIfWordIsInTextFile(item)){ 
//As per  @rishi007bansod suggestion: If we remove an item, then the next item will be shifted into this index & effectively skipped.  Therefore we want the index not to change this time around so decrement i after usage
    listToReorder.remove(i--);
    listToReorder.add(item);
  }
}
Run Code Online (Sandbox Code Playgroud)

其他选项

  • 根据@Andriy Kryvtsuns 的回答,您可以创建一个新的临时列表并按照您想要的顺序重新创建该列表,但这会使代码变得复杂。另一个问题是你不知道List传入的是什么实现,如果一个完整的列表LinkedList被传入并且remove()可以比线性时间运行得更快,那么创建整个列表可能效率低下。

更多高级选项

  • 您可以使用 for-each 循环(如@Ash French),但您需要使用Iteratoras for-each 循环来限制您编辑正在循环的集合

  • 根据@Mad Matts 优雅的解决方案,您可以获得所有 Java 8 并使用lambda