Checking if a String is contained in an Enum Set in O(1)
One of the choices is to use the valueOf
method of enum
but it's time complexity depends on the input which you'll be using.
If most of your inputs are nonconvertible to Utils
enum then making a set
and using contains
method is best approach as valueOf
method doesn't work well with values which are nonconvertible.
References:
Java enum valueOf efficiency
Java: Check if enum contains a given string?
This should do it:
public static boolean contains(String test) {
for (Choice c : Choice.values()) {
if (c.name().equals(test)) {
return true;
}
}
return false;
}
This way means you do not have to worry about adding additional enum values later, they are all checked.
Edit: If the enum is very large you could stick the values in a HashSet:
public static HashSet<String> getEnums() {
HashSet<String> values = new HashSet<String>();
for (Choice c : Choice.values()) {
values.add(c.name());
}
return values;
}
Then you can just do: values.contains("your string")
which returns true or false.
Best way to check if list contains at least one of an enum
A List<String>
never contains a PermissionsEnum
value.
The condition list.contains(enum.ABC) || list.contains(enum.XYZ)
is not going to be working.
Instead, you could map PermissionsEnum.values()
to a Stream<String>
and call Stream#anyMatch
on it:
boolean result = Arrays.stream(PermissionsEnum.values())
.map(PermissionsEnum::getValue)
.anyMatch(list::contains);
*I assumed that constructor parameter is accessible by the getValue
method.
In case the list is large (a few iterations over it might take a lot of time) we could optimise the previous snippet a bit and iterate over the list once:
Set<String> values = Arrays.stream(PermissionsEnum.values())
.map(PermissionsEnum::getValue)
.collect(Collectors.toSet());
boolean result = list.stream().anyMatch(values::contains);
How to check if a given string is a part of any given Enum in Java?
The simplest (and usually most efficient) way is as follows:
public <E extends Enum<E>> boolean isInEnum(String value, Class<E> enumClass) {
for (E e : enumClass.getEnumConstants()) {
if(e.name().equals(value)) { return true; }
}
return false;
}
and then you call isInEnum(filter, Filter.class)
.
Check if string contains at least one part of an enum
your emum...
public enum MyEnum
{
@this,
@is,
an,
@enum
}
... to check ...
var myString = "here I have a sample string containing an enum";
var found = Enum.GetNames(typeof(MyEnum)).Any(e=>myString.Contains(e));
Check if enum exists in Java
I don't think there's a built-in way to do it without catching exceptions. You could instead use something like this:
public static MyEnum asMyEnum(String str) {
for (MyEnum me : MyEnum.values()) {
if (me.name().equalsIgnoreCase(str))
return me;
}
return null;
}
Edit: As Jon Skeet notes, values()
works by cloning a private backing array every time it is called. If performance is critical, you may want to call values()
only once, cache the array, and iterate through that.
Also, if your enum has a huge number of values, Jon Skeet's map alternative is likely to perform better than any array iteration.
Check if list contains at least one of another - enums
Collections.disjoint
returns true
if the two specified collections have no elements in common. If it returns false
, then your list has at least one of the enums.
boolean contains = !Collections.disjoint(list, EnumSet.allOf(PermissionsEnum.class)));
A Stream API approach could be:
EnumSet<PermissionsEnum> set = EnumSet.allOf(PermissionsEnum.class);
boolean contains = list.stream().anyMatch(set::contains);
(similar to an iterative approach but with parallelisation included)
Related Topics
How to Resolve Java.Lang.Noclassdeffounderror: Javax/Xml/Bind/Jaxbexception
How to Create Comma Separated String in Single Quotes from Arraylist of String in Java
Kafka: How to Delete Records from a Topic Using Java API
Adb Cannot Connect to Daemon At Tcp:5037
Password Validate 8 Digits, Contains Upper, Lowercase, and a Special Character
How to Upload a Document to Sharepoint With Java
Using an Empty Keystore Password Used to Be Possible
Passing Data into HTML from Java Via Spring
How to Return Different Results When Calling the Same Mocked Method
Java H2 In-Memory Database Error: Table Not Found
Broadcast Receiver Is Not Working When Application Is Removed from Background
Testing Two Json Objects for Equality Ignoring Child Order in Java
Escaping New Line Character Within SQL Query
Calculating the Angle Between Two Lines Without Having to Calculate the Slope (Java)
Notifydatasetchanged() Makes the List Refresh and Scroll Jumps Back to the Top
Converting Number Representing a Date in Excel to a Java Date Object
I Get a Status 200 When Connecting to the Websocket, But It Is an Error