如何在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
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短