[英]Linked list doesn't contain values greater than a certain number
How can I create a method that would check whether or not a linked list contains any number larger than a parameter? 如何创建一种方法来检查链表是否包含大于参数的数字?
Let's say we have the linked list 假设我们有链表
[ 8 7 1 3 ]
. [ 8 7 1 3 ]
。 This would return true
and 这将返回true
并且
[ 10 12 3 2]
would return false
. [ 10 12 3 2]
将返回false
。
Would this work? 这行得通吗?
public boolean f(int k) {
for (int=0; int<linkedList.size(); i++) {
if (linkedList.get(i)>k)
return false;
}
else
return true;
}
Also, I need to mention, this method would not change the list in any way and it should still work if the list contains null elements. 另外,我需要提及的是,此方法不会以任何方式更改列表,并且如果列表包含null元素,它仍然可以工作。
Thanks! 谢谢!
With Java 8 使用Java 8
public boolean f(int k) {
return !linkedList.stream().anyMatch(i-> i> k );
}
clarification : I assume that you want to return false from the method in the case that even a single element is higher then the given k
. 说明 :我假设您要从方法中返回false,即使单个元素都比给定的k
。 Hence I use anyMatch since we only need to look for one element that is higher. 因此,我使用anyMatch,因为我们只需要查找一个更高的元素。 There is no need to loop over the whole list. 无需遍历整个列表。
No this will not work how you have it currently. 不,这将无法正常工作。 You need to loop through the whole list before returning. 返回之前,您需要遍历整个列表。 The only time you should return prematurely is if you find a reason to return false
in this context. 唯一应该过早返回的时间是在这种情况下是否找到return false
的原因。 So move your return true
outside of your loop and then you'd be fine. 因此,将您的return true
移到循环之外,然后就可以了。
Also, try to give meaning to your method and class definitions. 另外,请尝试为您的方法和类定义赋予含义。 Saying obj.f(12)
doesn't really say much, whereas obj.noElementGreaterThan(12)
says a lot more. 说obj.f(12)
并不能说太多,而obj.noElementGreaterThan(12)
说更多。
for example: 例如:
public boolean noElementGreaterThan( int k ) {
for( int i = 0; i < linkedList.size(); i++ )
{
if( linkedList.get(i) > k )
return false;
}
return true;
}
The reason this works is because it will loop through the entire list of objects, comparing each to the value passed in ( k
). 之所以起作用,是因为它将遍历整个对象列表,并将每个对象与( k
)中传递的值进行比较。 If the value is greater than k
, then it will return false
, meaning in this case that it does have an element greater than k
. 如果该值大于k
,则它将return false
,这意味着在这种情况下它确实具有一个大于k
的元素。
using streams you could do like this: 使用流,您可以这样做:
public boolean f(int k) {
List<Integer> filtered = linkedList.stream().filter(i -> i > k).collect(Collectors.toList());
return !filtered.isEmpty();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.