[英]Java compare elements from an array in an arraylist
我正在尝试将输入与数组列表中的值进行比较。
public compare(number)
前任; 我有一个数组列表:
[100,1102,14051,1024, / 142,1450,15121,1482,/ 141,1912,14924,1001] // the / represents each entry
数组的每个索引代表我程序中的一个唯一属性。 例如,索引 0 表示user id
,索引 1 表示room number
等。如果我执行arraylist.get(2)
它返回第二个数组(142,1450,15121,1482)
。
我正在尝试将number
与每个数组中的第二个元素进行比较。 所以说我运行这个compare(1102)
,我希望它遍历每个数组中的每个 [1] ,如果该索引匹配,则返回 true 。
所以我希望它将“数字”(1102)与每个第一个索引元素(1102,1450,1912)
并且因为 1102 在(1102,1450,1912)
,所以返回 true
我一直在四处寻找,但找不到如何实现这一点,或者以正确的方式提出问题
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 中找到匹配
直接的方法是使用增强的 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
迭代您的列表并比较每个第二个元素:
public static boolean compare (int number){
for( int i = 0; i<arraylist.size(); i++){
if(number == arraylist.get(i)[1]){
return true;
}
}
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.