3 回答

TA貢獻(xiàn)1877條經(jīng)驗 獲得超6個贊
Stream API 可以做到這一點。
public class MyCompare
{
private static Optional<Integer> compare(Integer valueToCompare)
{
Optional<Integer[]> matchingArray = listToCompare.stream()
.filter(eachArray -> eachArray[1].equals(valueToCompare))
.findFirst();
if(matchingArray.isPresent())
{
for(int i = 0; i < listToCompare.size(); i++)
{
if(listToCompare.get(i).equals(matchingArray.get()))
{
return Optional.of(i);
}
}
}
return Optional.empty();
}
private static List<Integer[]> listToCompare = new ArrayList<>();
public static void main(String[] args)
{
listToCompare.add(new Integer[] { 100, 1102, 14051, 1024 });
listToCompare.add(new Integer[] { 142, 1450, 15121, 1482 });
listToCompare.add(new Integer[] { 141, 1912, 14924, 1001 });
Optional<Integer> listIndex = compare(1102);
if(listIndex.isPresent())
{
System.out.println("Match found in list index " + listIndex.get());
}
else
{
System.out.println("No match found");
}
}
}
在列表索引 0 中找到匹配項

TA貢獻(xiàn)2021條經(jīng)驗 獲得超8個贊
遍歷您的列表并每隔一個元素進(jìn)行比較:
public static boolean compare (int number){
for( int i = 0; i<arraylist.size(); i++){
if(number == arraylist.get(i)[1]){
return true;
}
}
return false;
}

TA貢獻(xiàn)1836條經(jīng)驗 獲得超5個贊
直接的方法是使用增強(qiáng)的 for 循環(huán):
for (int[] items : list) {
// do your checking in here
}
更高級但更優(yōu)雅的方法是使用流:
list.stream() // converts the list into a Stream.
.flatMap(...) // can map each array in the list to its nth element.
.anyMatch(...); // returns true if any value in the stream matches the Predicate passed.
流 API:https ://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html
添加回答
舉報