如何在Java中搜索列表中的元素?
让我们首先创建一个String数组:
String arr[] = { "One", "Two", "Three", "Four", "Five" };
现在将上面的数组转换为List:
ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr));
对集合进行排序:
Collections.sort(arrList);
现在,在列表中找到元素“四个”。我们将获得找到指定元素的索引:
int index = Collections.binarySearch(arrList, "Four");
示例
import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; public class Demo { public static void main(String args[]) { String arr[] = { "One", "Two", "Three", "Four", "Five" }; ArrayList<String> arrList = new ArrayList<String>(Arrays.asList(arr)); Collections.sort(arrList); System.out.println(arrList); int index = Collections.binarySearch(arrList, "Four"); System.out.println("The element exists at index = " + index); } }
输出结果
[Five, Four, One, Three, Two] The element exists at index = 1