1import java.util.Arrays;
2
3// For String
4String[] array = {"Boto", "Nesto", "Lepta"};
5String toSearch = "Nesto";
6
7// Inline
8if (Arrays.toString(array).contains(toSearch)) {
9 // Do something if it's found
10}
11
12// Multi line
13String strArray = Array.toString(array);
14if (strArray.contains(toSearch)) {
15 // Do your thing
16}
17
18// Different elements
19int[] numbers = {1, 2, 3, 4, 5, 6, 7, 8, 9, 0};
20int number = 5;
21
22String checker = Arrays.toString(numbers);
23
24// The toString of int in some cases can happen without explicitly saying so
25// In this example we convert both
26if (checker.contains(Integer.toString(number)) {
27 // Found.
28}
29
1package com.mkyong.core;
2
3import java.util.Arrays;
4import java.util.List;
5
6public class StringArrayExample1 {
7
8 public static void main(String[] args) {
9
10 String[] alphabet = new String[]{"A", "B", "C"};
11
12 // Convert String Array to List
13 List<String> list = Arrays.asList(alphabet);
14
15 if(list.contains("A")){
16 System.out.println("Hello A");
17 }
18
19 }
20
21}
22Copy
1StringArrayExample1.java
2
3package com.mkyong.core;
4
5import java.util.Arrays;
6import java.util.List;
7
8public class StringArrayExample1 {
9
10 public static void main(String[] args) {
11
12 String[] alphabet = new String[]{"A", "B", "C"};
13
14 // Convert String Array to List
15 List<String> list = Arrays.asList(alphabet);
16
17 if(list.contains("A")){
18 System.out.println("Hello A");
19 }
20
21 }
22
23}
1 // Convert to stream and test it
2 boolean result = Arrays.stream(alphabet).anyMatch("A"::equals);
3 if (result) {
4 System.out.println("Hello A");
5 }
6Copy
1public class Contains {
2
3 public static void main(String[] args) {
4 int[] num = {1, 2, 3, 4, 5};
5 int toFind = 3;
6 boolean found = false;
7
8 for (int n : num) {
9 if (n == toFind) {
10 found = true;
11 break;
12 }
13 }
14
15 if(found)
16 System.out.println(toFind + " is found.");
17 else
18 System.out.println(toFind + " is not found.");
19 }
20}