通过传递一个字符串并将这个字符串放在最后一个索引处,对 Java List<String> 进行排序

我在列表中的任何位置都有一个字符串,并通过参数传递一个字符串,我需要检查是否有相同的元素,并将其放在列表的末尾,通过重新排序其他元素索引。


它会是这样的:


初始列表:“A”、“B”、“C”、“D”、“E”


输入参数:“B”


如果初始列表中有“B”:重新排序初始列表。


重新排序的列表:“A”、“E”、“C”、“D”、“B”


 private void reorderList(List<String> list, String name) {

    for (int i = 0; i < list.size(); i++) {

        if (list.get(i).equals(name)) {


        }

    }

}

我怎样才能做到这一点?


阿晨1998
浏览 205回答 3
3回答

缥缈止盈

不要忘记,它List可能有多个相同的元素。如果是这样,那么所有这些都应该移到最后。您可以使用它Iterator同时查找和删除所需的元素。之后,只需将所需数量的元素添加到列表的末尾。使用这种方法,您只迭代列表一次,这是O(n)。private static void reorderList(List<String> list, String name) {&nbsp; &nbsp; Iterator<String> it = list.iterator();&nbsp; &nbsp; int total = 0;&nbsp; &nbsp; while (it.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; if (name.equals(it.next())) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; it.remove();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; total++;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; for (int i = 0; i < total; i++)&nbsp; &nbsp; &nbsp; &nbsp; list.add(name);}

宝慕林4294392

很简单:首先迭代列表,并检查是否有匹配的索引如果是这样,请记住该索引并打破循环那么:使用List.remove(INT)以除去该匹配的索引最后:将您的参数(与删除的字符串匹配!)附加到列表的末尾诀窍是前面提到的remove()也会将任何后续元素向左移动。

慕田峪4524236

记得使用提供的工具java.util.List。您可以使用它List.contains(Object)来查找字符串是否存在。现在,List.indexOf(Object)将它在列表中的索引作为 int 返回。List.remove(int)&nbsp;将从列表中删除给定的索引。List.add(Object), 将添加到列表的末尾。只是提示,for如果您使用我刚才提到的功能,则不需要。另外,请记住字符串是对象。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java