Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
281 views
in Technique[技术] by (71.8m points)

syntactic sugar - Java in operator

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...