运营商中的Java [英] Java in operator

查看:114
本文介绍了运营商中的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在第一百万次,我本想在Java中使用 IN 运算符,类似于 IN SQL中的运算符。它可以作为编译器语法糖实现。所以这个

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)) {
}

或者类似于 int long 和类似类型:

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.

类似这样的东西会成为Java 8的一部分吗?如果没有,我怎么能提出这样的建议呢?或者我现在可以使用任何等效的构造吗?

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?

推荐答案

使用 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)) {
}

这篇关于运营商中的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆