问题
For the one millionth time, I would have liked to use an IN
operator in Java, similar to the IN
operator in SQL. It could just be implemented as compiler syntactic sugar. So this
if (value in (a, b, c)) {
}
else if (value in (d, e)) {
}
...would really be awesome. In fact, the above is the same as the rather verbose (and not adapted for primitives) construct here:
if (Arrays.asList(a, b, c).contains(value)) {
}
else if (Arrays.asList(d, e).contains(value)) {
}
Or like this for int
, long
and similar types:
switch (value) {
case a:
case b:
case c:
// ..
break;
case d:
case e:
// ..
break;
}
Or maybe there could be even more efficient implementations.
Question:
Is something like this going to be part of Java 8? How can I make such a suggestion, if not? Or is there any equivalent construct that I could use right now?
回答1:
Using op4j:
Op.onListFor(a,b,c).get().contains(value);
Using the same approach, you could create a helper classes Is
with a method in
:
class Is<T> {
private T value;
public Is( T value ) { this.value = value; }
public boolean in( T... set ) {
for( T item : set ) {
if( value.equals( item ) ) {
return true;
}
}
return false;
}
public static <T> Is<T> is( T value ) {
return new Is<T>( value );
}
}
with a static import, you can write:
if(is(value).in(a,b,c)) {
}
回答2:
You can write a helper method to do it.
public static <T> boolean isIn(T t, T... ts) {
for(T t2: ts)
if (t.equals(t2)) return true;
return false;
}
// later
if (isIn(value, a,b,c)) {
} else if (isIn(value, d,e)) {
}
回答3:
There has been a very old proposal for collection literals.
Currently there is Sets.newHashSet in Guava which is pretty similar to Arrays.asList
.
回答4:
You are looking for the Java Community Process
回答5:
I doubt something like an IN operator would be made available, as there are already multiple ways of doing this(like using switch) as you yourself pointed out.
And I think requirement list for project-coin and J8 is already fully loaded to be anything like this to be considered.
来源:https://stackoverflow.com/questions/7390571/java-in-operator