3 回答
TA贡献1877条经验 获得超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贡献2021条经验 获得超8个赞
遍历您的列表并每隔一个元素进行比较:
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贡献1836条经验 获得超5个赞
直接的方法是使用增强的 for 循环:
for (int[] items : list) {
// do your checking in here
}
更高级但更优雅的方法是使用流:
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
添加回答
举报