How to use Lambda expressions in java for nested if-else and for loop together
Here's the solution: it cycles all element in your list checking if are all the same.
You can try adding or editing the list so you can have different outputs. I've written the logic, you can easly put it into a JUnit test
List<String> names= new ArrayList<>();
names.add("John");
names.add("Mark");
String firstEntry = names.get(0);
boolean allMatch = names.stream().allMatch(name -> firstEntry.equals(name));
System.out.println("All names are the same: "+allMatch);
How to perform nested 'if' statements using Java 8/lambda?
The essential observation here is that your problem involves a non-isomorphic transformation: a single input element may map to zero, one, or two output elements. Whenever you notice this, you should immediately start looking for a solution which involves flatMap
instead of map
because that's the only way to achieve such a general transformation. In your particular case you can first apply filter
for a one-to-zero element mapping, then flatMap
for one-to-two mapping:
List<Integer> result =
IntStream.rangeClosed(1, 10)
.filter(i -> 10 % i == 0)
.flatMap(i -> i == 5 ? IntStream.of(i) : IntStream.of(i, 10 / i))
.boxed()
.collect(toList());
(assuming import static java.util.stream.Collectors.toList
)
Can be convert following java code to Lambda expression?
Instead of creating a class (your K
class) that implements Predicate<Prescription<D, I>>
, you can assign a lambda expression to a Predicate
variable.
For example:
Predicate<Prescription<BaseDose<DoseInstance>, DoseInstance>> pred =
p -> DepositType.DATE == p.getBaseDeposit().getDepositType();
If you need a lambda expression with multiple statements, you can write:
Predicate<Prescription<BaseDose<DoseInstance>, DoseInstance>> pred =
p -> {
final SigningStatus signingStatus = p.getSigningStatus();
return !p.isReplacedByLatest() && SigningStatus.INVALIDATED.equals(signingStatus);
};
though this can be simplified to a single statement:
Predicate<Prescription<BaseDose<DoseInstance>, DoseInstance>> pred =
p -> !p.isReplacedByLatest() && SigningStatus.INVALIDATED.equals(p.getSigningStatus());
How to convert a string to a lambda expression?
Marko's comment on the question is correct. You can't read a bare Java lambda expression out of a file, since such an expression isn't defined without a target type provided by the context. For example, consider the following method declarations:
void method1(BiFunction<String,String,String> f) { ... }
void method2(BiFunction<Integer,Integer,Integer> f) { ... }
Then in the following code,
method1((x, y) -> x + y);
method2((x, y) -> x + y);
the two lambda expressions (x, y) -> x + y
mean completely different things. For method1, the +
operator is string concatenation, but for method2, it means integer addition.
This is wandering a bit far afield from your question, but you can read and evaluate a lambda or function expression using a dynamic language. In Java 8 there is the Nashorn JavaScript engine. So instead of attempting to read an evaluate a Java lambda expression, you could read and evaluate a JavaScript function using Nashorn, called from Java.
The following code takes a function in arg[0] and applies it to each subsequent, printing the results:
import java.util.function.Function;
import javax.script.*;
public class ScriptFunction {
public static void main(String[] args) throws Exception {
ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
@SuppressWarnings("unchecked")
Function<Object,Object> f = (Function<Object,Object>)engine.eval(
String.format("new java.util.function.Function(%s)", args[0]));
for (int i = 1; i < args.length; i++) {
System.out.println(f.apply(args[i]));
}
}
}
For example, running the command
java ScriptFunction 'function(x) 3 * x + 1' 17 23 47
gives the results
52.0
70.0
142.0
The wrapping of the function string inside of new java.util.function.Function
is necessary in order to create an adapter between Nashorn's notion of a JavaScript function and Java's Function interface. (There might be a better way, but I'm not aware of one.) The cast of the return value of eval
to Function<Object,Object>
results in an unchecked cast warning, which is unavoidable, I think, since this is the boundary between JavaScript, a dynamically-typed language, and Java, which is statically-typed. Finally, no error checking is done. I'm sure this will blow up in a variety of nasty ways if certain assumptions are violated, such as the first argument not actually representing a JavaScript function.
Still, you might find this technique useful if you have a need to evaluate expressions or functions read from a file.
Related Topics
Write to Text File from Multiple Threads
Printing a Statement Only Once in a While Loop
How to Check Type of Variable in Java
Regular Expression for Uppercase Letters in a String
@Responsebody , Responseentity Spring Return Object as Json
Java Spring: Best Way to Convert a File to a Multipartfile
How to Prevent Duplicate Results in Hibernate
Jparepository Findall() Returns Empty Result
Dynamically Change Application.Properties Values in Spring Boot
Multipartexception: Current Request Is Not a Multipart Request
How Many Times Will This Loop Execute
How to Set Default Download Directory in Selenium Chrome Capabilities
How to Set a Default Entity Property Value With Hibernate
Java How to Retrieve More Than 1 Million Rows in a Resultset
Eclipse Problems View Not Showing Errors Anymore
How to Determine If a List of String Contains Null or Empty Elements
How to Solve Liquibase Checksum Validation Fail After Liquibase Upgrade