如何在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 教师闺蜜祝福语简短