此示例将使用 java、guava 和 apache commons实现在数组中查找给定原始值或对象值的索引。
在使用核心 jdk 时,我们将创建一个字符串和整数数组,然后调用 Arrays.asList 转换为数组列表。接下来我们将调用 ArrayList.indexOf ,它将返回此列表中指定元素第一次出现的索引。
@Test
public void element_index_in_array_java () {
String[] lilyFlowers = {
"Lily of the valley",
"Lily Elite",
"Lily Monte Negro",
"Lily Casa Blanca",
"Lily of the Nile – Alba",
"Lily Stargazer"};
int indexOfFlower = Arrays.asList(lilyFlowers).indexOf("Lily Monte Negro");
assertEquals(2, indexOfFlower);
}
@Test
public void element_index_in_int_array_java () {
Integer[] twoQuarters = {1, 2, 3, 4, 5, 6};
int endOfFirstQuarter = Arrays.asList(twoQuarters).indexOf(3);
assertEquals(2, endOfFirstQuarter);
}
使用 guava 的 Iterators 类,我们将向 Iterators.indexOf 传递一个Predicate,它将返回满足所提供Predicate的第一个元素的索引,或者在这种情况下匹配“Lily Elite”。
@Test
public void element_index_in_array_java_with_guava () {
String[] lilyFlowers = {
"Lily of the valley",
"Lily Elite",
"Lily Monte Negro",
"Lily Casa Blanca",
"Lily of the Nile – Alba",
"Lily Stargazer"};
int indexOfFlower = Iterators.indexOf(Iterators.forArray(lilyFlowers), new Predicate<String>() {
public boolean apply(String input) {
return input.equals("Lily Elite");
}
});
assertEquals(1, indexOfFlower);
}
要使用 guava 查找原始数组的索引,我们将使用 Ints 类,该类包含与 int 基元有关的静态实用方法。 Ints.indexOf 将返回指定值的第一个外观的索引,在本例中为 3。
@Test
public void element_index_of_ints_in_array_java_with_guava () {
int [] twoQuarters = {1, 2, 3, 4, 5, 6};
int lastMonthInFirstQuarter = Ints.indexOf(twoQuarters, 3);
assertEquals(2, lastMonthInFirstQuarter);
}
Apache commons ArrayUtils 类包含对原始数组或对象数组的操作。我们将 ArrayUtils.indexOf 查找数组中给定值的索引。
@Test
public void element_index_of_string_array_java_with_apache_commons() {
String[] lilyFlowers = { "Lily of the valley", "Lily Elite",
"Lily Monte Negro", "Lily Casa Blanca",
"Lily of the Nile – Alba", "Lily Stargazer" };
int indexOfFlower = ArrayUtils.indexOf(lilyFlowers, "Lily Elite");
assertEquals(1, indexOfFlower);
}
@Test
public void element_index_of_int_array_java_with_apache_commons() {
int [] twoQuarters = {1, 2, 3, 4, 5, 6};
int lastMonthInFirstQuarter = ArrayUtils.indexOf(twoQuarters, 3);
assertEquals(2, lastMonthInFirstQuarter);
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : http://www.leveluplunch.com/java/examples/find-element-index-in-array/
内容来源于网络,如有侵权,请联系作者删除!