Java如何搜索集合元素?
本示例使用Collections.binarySearch()来搜索指定集合内的指定对象。在调用该binarySearch()方法之前,我们需要对集合的元素进行排序。如果未按对象的自然顺序对对象进行排序,则搜索结果将不确定。
package org.nhooo.example.util;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Collections;
import java.text.DateFormatSymbols;
public class CollectionSearch {
public static void main(String[] args) {
DateFormatSymbols dfs = new DateFormatSymbols();
LinkedList<String> monthList = new LinkedList<>();
monthList.addAll(Arrays.asList(dfs.getMonths()));
//排序集合元素
Collections.sort(monthList);
System.out.println("Months = " + monthList);
//获取11月在monthList中的位置。返回正数
//如果在monthList中找到该项目,则返回值。
int index = Collections.binarySearch(monthList, "November");
if (index > 0) {
System.out.println("Found at index = " + index);
System.out.println("Month = " + monthList.get(index));
}
}
}上面的代码片段的输出如下。
Months = [, April, August, December, February, January, July, June, March, May, November, October, September] Found at index = 10 Month = November
热门推荐
10 诗词送行祝福语大全简短
11 新房开工吉日祝福语简短
12 50多岁生日简短祝福语
13 安徽疫情祝福语简短英语
14 农民朋友发财祝福语简短
15 对生活祝福语简短精辟
16 搬家词简短祝福语朋友
17 女神结婚快乐祝福语简短
18 文学短句祝福语大全简短