¿La forma más concisa de hacer "no contenido en"?

Coming from Haskell I was used to have concise operators like

not ("x" `elem` ["a","b","c"])

What is the most concise way to do that in plain old java, e.g. for an if-clause?

Lists? Arrays? Helper-Function? That feels so ugly and overly verbose ...

preguntado el 31 de enero de 12 a las 08:01

Aún más conciso: notElem "x" ["a","b","c"]. -

7 Respuestas

Consulta contains method in java collections:

por ejemplo:

ArrayList<String> arrList = new ArrayList<String>();
arrList.add("One");
arrList.add("Two");
arrList.add("Three");

if( ! arrList.contains("Four"))
{
    System.out.println("item not contained");
}

Respondido el 31 de enero de 12 a las 12:01

I accept this one for further discussion. Someone notes the 4 long lines compared to the Haskell approach ? - Bastl

@Bastl well, you could shorten it up a bit: ! Arrays.asList("One", "Two", "Three").contains("Four"). If you're worried about extra clutter going from Haskell to Java, this is going to be the least of your problems... :) - yshavit

ah yes, that looks ok to me :-) nearly looks like composing functions. - Bastl

@Bastl: you can sort of think of . as flowing the other way in function composition. baz . bar $ foo traduce a foo.bar().baz() - Dan Burton

Collection#contains

 if(!collection.contains(object))

Respondido el 31 de enero de 12 a las 12:01

but you have to create the collection object first :-/ - Bastl

Echa un vistazo a lambdaj project. It will give you back some of the functional tools you miss.

Respondido el 31 de enero de 12 a las 12:01

Con Guayaba:

!ImmutableList.of("a", "b", "c").contains("x")

Respondido el 31 de enero de 12 a las 13:01

Con Frege:

not ("x" `elem` ["a","b","c"])

The Java code will be generated by the compiler.

Respondido el 31 de enero de 12 a las 14:01

You can do it with any collection: !collection.contains(x). Una Set, y en particular HashSet, is probably going to be the fastest for this kind of operation.

Respondido el 31 de enero de 12 a las 12:01

If you want a character lookup, you can use

if ("abc".indexOf(ch) < 0)

Respondido el 31 de enero de 12 a las 12:01

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.