如何在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 农民朋友发财祝福语简短