[英]Check a collection if it contains all the values that match a certain value
我想知道哪種最佳方法可以知道某個集合的所有值是否都與某個特定值匹配。
List<Integer> listOfStrings = new ArrayList<Integer>();
我只想知道“ listOfStrings”中的所有條目是否都與一個特定值匹配; 例如,沒有不為“ 1”的整數。
我需要最快的解決方案。 我有一個解決方案,但是非常簡單。
循環遍歷:
public boolean checkAll(ArrayList<String> list) {
for(int i = 0; i < listOfStrings.size(); i++) {
String candidate = listOfStrings.get(i);
if(candidate == null || !candidate.equals("1")) {
return false;
}
}
return true;
}
您可以使用簡單的for
循環遍歷列表,然后將每個值與您的特定值進行比較(例如1)。 如果列表中的一個值不等於特定值,則將布爾值設置為false。
做這個
public boolean isFilled(String value, ArrayList<String> list)
{
for(int i = 0; i < list.size(); i++)
{
String toTest = list.get(i);
if(toTest == null || !toTest.equals(value)) {
return false;
}
}
return true;
}
在Java 8中,可以使用流的allMatch
方法來實現此目的。
public boolean allOnes(Collection<Integer> values) {
return values.parallelStream().allMatch(i -> i == 1);
}
如果有多個處理器,使用parallelStream
可能會產生更好的性能。
boolean x=true;
ArrayList<Integer> listOfInts = new ArrayList<Integer> (Arrays.asList(5,3,1,2,9,5,0,7));
Integer target = 1;
for (int i = 0; i < listOfInts.size(); i++)
{
if (listOfInts.get(i).equals(target)) // nothing
{
} else {
x = false;
break;// exits loop right after this
}
}
System.out.println(x);
令我驚訝的是,到目前為止提出的所有解決方案都是錯誤的,或者包含一個細微的錯誤,或者可能更有效。
無論列表類型如何,即使列表包含null元素,此解決方案都可以快速運行:
public boolean listIsFilledWith(List<Integer> integers, int i) {
Integer value = i; // transform the int into an Integer only once
for (Integer element : integers) { // iterate using an iterator, to avoid performance problems with linked lists
if (!value.equals(element)) { // value is not null, but element can be. Don't compare objects with == or !=
return false; // return early
}
}
return true;
}
使用.contains()
方法,該方法告訴您列表中是否存在該值: http : .contains()
。 lang.Object 29%
myList.contains(1);
注意:它使用所包含對象的.equals()
方法(在將來的開發中可能會很有用)。
HIH M.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.