if (item *在* array 中) { Java }

huangapple go评论78阅读模式
英文:

if item *in* array java

问题

我是一名学习Java的Python程序员。

我遇到了以下的问题(或者说复杂情况可能更合适):

在Python中,我可以轻松地在if语句中检查一个项是否在列表中,就像这样:

x = 1
if x in [0,1,2,3,4,5]:
    #做点什么

在Java中怎么做最方便?

  • 是否可以不使用像上面示例中的列表变量来实现?

例如:

new HashSet<>(Arrays.asList(0, 1)).contains(1);

>(不确定是否重复,我查过了,如果是,请务必标记一下=)

英文:

I'm a python programmer who is learning java

I ran across the following problem (or maybe complication is a better term to use)

In python, I can easily check if an item is in a list within an if statement like so:

x = 1
if x in [0,1,2,3,4,5]:
    #do something

what is the easiest way to do that in java?

  • can I do it without using a list variable like in the example above?

e.g

{0,1}.contains(1)

>(not sure if this is a duplicate, I did look, if it is be sure to flag it for =)

答案1

得分: 4

尝试这样写:

if (Arrays.asList(array).contains("---something---"))
英文:

Try this:

if (Arrays.asList(array).contains(&quot;---something---&quot;))

答案2

得分: 3

另一种方法可能会对您有所帮助。

如果数组元素是连续序列,请使用:

int x = 1;
if (IntStream.range(0, 6).anyMatch(value -> value == x)) {
	// 做一些类似于打印消息的操作
	System.out.println("找到 x");
}

如果数组的元素是非连续序列:

int x = 1;
int[] inputs = new int[] {0, 1, 2, 3, 4, 5, 8, 9, 10};
if (Arrays.stream(inputs).anyMatch(value -> value == x)) {
	// 做一些类似于打印消息的操作
	System.out.println("找到 x");
}
英文:

Another method may help you.

If the array element is consecutive sequenceuse:

int x = 1;
if (IntStream.range(0, 6).anyMatch(value -&gt; value == x)) {
	// do something like print message
	System.out.println(&quot;find x&quot;);
}

If the element of array is non-contiguous sequence:

int x = 1;
int[] inputs = new int[] {0, 1, 2, 3, 4, 5, 8, 9, 10};
if (Arrays.stream(inputs).anyMatch(value -&gt; value == x)) {
	// do something like print message
	System.out.println(&quot;find x&quot;);
}

答案3

得分: 1

这里我使用数组,这意味着一旦创建数组,就无法更改其大小,然后我通过一个for循环解析数组,并检查我的值 x 是否等于循环的迭代 imyArray 中的值。

public static void main(String[] args) {
        int x = 2;
        int [] myArray = {1,2,3,4,5};
        for (int i = 0; i &lt; myArray.length; i++) {
            if(x == myArray[i])
            {
                //做点什么
            }
        }   
    }
}

<details>
<summary>英文:</summary>

Here I use arrays, that means once u create a arrays u cant change his size, Then I parse the arrays with a for loop and check if my values ``` x ``` is equals to my values in ``` myArrays ``` in the iteration ``` i ``` of the loop. 

public static void main(String[] args) {
int x = 2;
int [] myArray = {1,2,3,4,5};
for (int i = 0; i < myArray.length; i++) {
if(x == myArray[i])
{
//do something
}
}
}
}

huangapple
  • 本文由 发表于 2020年10月15日 07:44:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/64362942.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定