我有一個的ArrayListŤJAVA檢查如果一個數組包含比給定
ArrayList<Integer> T = new ArrayList<Integer>();
的聲明,我有一個while循環應該是活動的,直到列表將被組成的僅值的值不同勢 - 1個int的。目前看起來像這樣:
while(T.contains(!-1))
正如你可能猜到的那樣。它不能正常工作,因爲我不能在整數上使用否定。
我有一個的ArrayListŤJAVA檢查如果一個數組包含比給定
ArrayList<Integer> T = new ArrayList<Integer>();
的聲明,我有一個while循環應該是活動的,直到列表將被組成的僅值的值不同勢 - 1個int的。目前看起來像這樣:
while(T.contains(!-1))
正如你可能猜到的那樣。它不能正常工作,因爲我不能在整數上使用否定。
但是,只有當ENTIRE列表由-1組成時,循環才結束。
您可以使用HashSet
,它將刪除列表中的所有重複元素。
如果HashSet
對象的大小爲1(表示該列表僅包含相同的值),並且列表的第一個元素爲-1
,則表示該列表僅包含-1
值。
List<Integer> integers = new ArrayList<Integer>();
while (!(new HashSet<Integer>(integers).size() == 1 && integers.get(0).intValue() == -1)){
....
}
您可以使用Stream#allMatch
。
while(!T.stream().allMatch(i -> i == -1)){ // note the ! operator to negate the result
//do something
}
這應該不斷循環,直到列表將僅由-1
整數爲你建議。
謝謝,這似乎解決了我的問題。 –
您可以流列表:
List<Integer> myList = ...;
myList = myList.stream().filter(x -> x < 0).collect(Collectors.toList());
System.out.println(myList);
如果你想重複檢查是否有不-1在列表中,你可以爲效率做如下元素:
n
while (n > 0) { do stuff; and decrease n if the value of an element becomes -1 }
*** T.contains(! - 1)*** ???這是什麼意思? –
問題是你正在使用「!」在錯誤的地方,wile循環與條件一起工作,並且你需要它的條件是「不包含」,試着把「!」在你的條件之前 –
是的,如果我使用 而不是(!T.contains(-1)) 上的否定,則循環將在FIRST -1 int落入T之後結束。但是,僅當ENTIRE列表爲由-1組成。 –