[英]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.