如何在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 兄妹拍照祝福语简短的话