How to Determine Whether an Array Contains a Particular Value in Java

How do I determine whether an array contains a particular value in Java?

Arrays.asList(yourArray).contains(yourValue)

Warning: this doesn't work for arrays of primitives (see the comments).


Since java-8 you can now use Streams.

String[] values = {"AB","BC","CD","AE"};
boolean contains = Arrays.stream(values).anyMatch("s"::equals);

To check whether an array of int, double or long contains a value use IntStream, DoubleStream or LongStream respectively.

Example

int[] a = {1,2,3,4};
boolean contains = IntStream.of(a).anyMatch(x -> x == 4);

Most efficient way to check if an array contains a value in Java?

Your co-worker is incorrect when they assert that your method is creating a new data structure.

If you look at the API for Arrays.asList(), it says that it

Returns a fixed-size list backed by the specified array.

There is no reason to write your own code to iterate over the array when you can just wrap a List around it, and use its built-in methods.

How can I verify that an array of strings contain a certain string?

Convert the array of valid directions to a list:

List valid = Arrays.asList(directions)

Or just declare it directly as:

List valid = Arrays.asList("UP", "DOWN", "RIGHT", "LEFT", "up", "down", "right", "left")

You can then use the contains method:

if (valid.contains(input)) {
// is valid
} else {
// not valid
}

Note that this won't match a mixed case input such as "Up" so you might want to store just the uppercase values in the list and then use valid.contains(input.toUpperCase())

How to java Program to Check if an array contains a given two different values?

This...

if (count == 2)
break;
isSuccess = true;

doesn't make sense. This will set isSuccess even if there is only one match

The long winded approach

Okay, let's assuming for a second that you only care if there is at least one start and one end (discounting duplicates). One approach would be to use to state flags, one for start and one for end. To keep it simple, they would start of as 0 but would only ever be a maximum of 1 (because we don't want duplicates), then you might be able to do something like...

public static boolean checkStartAndEndTimeTag(List<Tag> tags) {
boolean isSuccess = false;
int starts = 0;
int ends = 0;
for (Tag tag : tags) {
if (tag.getKey().equals("start")) {
starts = 1;
} else if (tag.getKey().equals("end")) {
ends = 1;
}
}
isSuccess = (starts + ends) == 2;
return isSuccess;
}

Ok, you don't need isSuccess = (starts + ends) == 2; and could simply return the result of the comparison. You could also break out of the loop if (starts + ends) == 2 and save yourself from unnecessary computation

for (Tag tag : tags) {
if (tag.getKey().equals("start")) {
starts = 1;
} else if (tag.getKey().equals("end")) {
ends = 1;
}

if ((starts + ends) == 2) {
break;
}
}

Using streams...

One approach might be to make use the streams support and simply filter the List and count the results, for example...

import java.util.ArrayList;
import java.util.List;

public class Test {

public static void main(String[] args) {
new Test();
}

public Test() {
List<Tag> tags = new ArrayList<Tag>(25);
tags.add(new Tag("begin"));
tags.add(new Tag("front"));
tags.add(new Tag("start"));
tags.add(new Tag("finish"));
tags.add(new Tag("tail"));
tags.add(new Tag("end"));

boolean isSuccessful = tags.stream().filter(tag -> tag.getKey().equals("start") || tag.getKey().equals("end")).count() >= 2;
System.out.println(isSuccessful);
}

public class Tag {
private String key;

public Tag(String key) {
this.key = key;
}

public String getKey() {
return key;
}


}
}

Updated...

Okay, this got complicated fast. Let's assume you don't want to match two start tags, so you MUST have both one end and one start tag

So, using the above, example, we can modify the Tag class to support equals (and by extension hashcode)

public class Tag {

private String key;

public Tag(String key) {
this.key = key;
}

public String getKey() {
return key;
}

@Override
public String toString() {
return getKey();
}

@Override
public int hashCode() {
int hash = 7;
hash = 73 * hash + Objects.hashCode(this.key);
return hash;
}

@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Tag other = (Tag) obj;
if (!Objects.equals(this.key, other.key)) {
return false;
}
return true;
}

}

Then we can simply use distinct to filter out any duplicates, for example...

boolean isSuccessful = tags
.stream()
.distinct()
.filter(tag -> tag.getKey().equals("start") || tag.getKey().equals("end"))
.count() >= 2;

Probably not the most efficient solution, but certainly one of the shortest

Check if an array has a value

Lets say you have a Coordinate class that holds 2 values for x and y. This class has methods like:

  • int getX(); to get the value of the x coordinate
  • int getY(); to get the value of the y coordinate

Now you also need a CoordinateContainer class that holds a number of Coordinates.

The Coordinate container class can have (among others..) methods like :

  • void add(Coordinate x); to add a Coordinate.
  • Coordinate getCoordinate(Coordinate x); to get a Coordinate
  • `boolean contains(Coordinate x); to check if the container contains a specific coordinate.

and so on.

Now you can represent a snake as a CoordinateContainer.

The implementation of the contains method can look like this:

public boolean contains(Coordinate x){
for(int i = 0; i < numOfCoordinates; i++) //numOfCoordinates is an int holding how many Coordinates you have passed in the array.
if(array[i].getX() == x.getX() && array[i].getY() == x.getY()) return true;
return false; // Compare value of X,Y of each Coordinate with the respective X,Y of the parameter Coordinate.
}

Now that you have a way to check if a Coordinate is contained in a CoordinateContainer you are good to go. The method to place apples can look like this:

private void placeNewApple(){
Coordinate newApple = apples.getRandom(); //<-- getRandom() returns a random Coordinate within the board
while(snake.contains(newApple)){
newApple = apples.getNew();
}
placeApple(newApple);// method to place an apple at newApple.getX() , newApple.getY();
}

Hope this makes sense

NOTE: If you don't have to/want to do it this way, i.e with seperate classes, and you only have an Array in a main programm please add some code to your questions and i will update my answer.

Checking if a value is in an array

Here's what you do

boolean choicesContainUserChoice = Arrays.asList(choices).contains(userChoice);

or if you care about performance a lot

boolean choicesContainUserChoice = false;
for (int i = 0; i < choices.length; i++ ) {
if (Objects.equals(choices[i], userChoice) {
choicesContainUserChoice = true;
break;
}
}


Related Topics



Leave a reply



Submit