Skip to content
Advertisement

Tag: syntax

Java – How do I create Predicates as Arrays.asList() arguments?

I have a few predicates that I want to put in a list so I can then call stream().noneMatch() on my list. I successfully did this by creating named Predicates but how can I create them within an Arrays.asList()’s argument list? Here’s the working code that I’d like to convert: I’d expect the result of the conversion to look something

In java, what’s the correct syntax for creating/constructing/defining a named variable on the same line as I add it to an arraylist?

I’m populating an arraylist in Java, and I’m wondering if it’s possible to cuts some lines by doing the following (except complete): myArraylist.add(new objectname varname (constructor things)); instead of: objectname varname = new objectname(constructor things); myArrayList.add(varname); Answer You can do the following (using a record as an example). But you won’t have any other named instances of the created classes.

Shorthand class constructor member initialisation

Writing simple constructors in Java is pretty verbose. For each field that needs to be initialised you need to write the variable name four times, e.g. like so: Is there a shorthand for that like e.g. in Kotlin? This question was asked before here: Shorthand class constructor field initialisation But that was way back in 2013 (6 Java versions ago)

Nested if-else behaviour without braces

Consider the following unformatted nested if-else Java code My question is: according to the Java language specifications, to what if does the else branch apply? By hand-reformatting and adding braces, which of these two is correct? Block 1: Block 2: Answer From the Java Language Specification: The Java programming language, like C and C++ and many programming languages before them,

Java switch statement multiple cases

Just trying to figure out how to use many multiple cases for a Java switch statement. Here’s an example of what I’m trying to do: versus having to do: Any ideas if this possible, or what a good alternative is? Answer Sadly, it’s not possible in Java. You’ll have to resort to using if-else statements.

Advertisement