lambda,java-8,optional , OrElseGet chaining in Java8

OrElseGet chaining in Java8


Tag: lambda,java-8,optional

I have a list in which 50 values are coming. Now I have 3 matching conditions, however matching conditions have some order. Like for P1 condition I have to match first, if it does not matches in any element then second condition should be evaluated for logic and so on. How to do this using Java 8 and orElseGet chaining.

I was considering to use orElseGet, but it requires a supplier.

Please let me know how to do it.


The simplest way would be to iterate over the conditions first:

Stream.<Predicate<String>>of("AB"::equals, "DC"::equals,"XY"::equals)
        .flatMap(condition ->

Of course, since in your sample case all conditions are matches to strings, you could do this simpler, but I assume you mean to ask about a general case.

You can also do it with orElseGet:"AB"::equals).findFirst()
        .map(Optional::of).orElseGet(() ->"DC"::equals).findFirst())
        .map(Optional::of).orElseGet(() ->"XY"::equals).findFirst())


Are interfaces a valid substitute for utility classes in Java 8? [duplicate]

This question already has an answer here: Java 8: Interface with static methods instead of static util class 4 answers For the past decade or so, I've been using the pattern below for my Java utility classes. The class contains only static methods and fields, is declared final so...

C# + linq(concat) rewrite to java

I have a code example in C# (with linq) but am trying to translate this to java code (java 8). But am getting very confused about what happens. Also i am not able to reproduce the same result in java as from the c# code. public IEnumerable<Node> GetNeighborNodes(Node v) {...

Use “Contains” to match part of string in lambda expression

I have this MVC page where I have three different "input" elements, all the same class, using the jQuery autocomplete. On any one of them I am doing this in the controller: [HttpGet] public ActionResult GetAllItemsEdit(string data, string source) { List<TextValuePair> items = InventoryControlRepository.GetAllItemsTVP(); var result1 = items.Where(item => item.Text.Contains(data.ToUpper())).ToList();...

Java 8: Filtering Map to List by person's status

I'm trying to filter a Map<Long, Person> people and return only the IDs of these people having a status of SUBSCRIBED in a List<Long>. Here is the code in the old-fashioned way: public List<Long> getSubscribedPeople() { final List<Long> subscribedPeople = new ArrayList<>(); for (final Map.Entry<Long, Person> entry : subscribedPeople.entrySet()) {...

Java8 Nested Streams write back with setter

I´m trying to loop over two lists, filter the nested list and write the result back into the main object with java8 features. locations.forEach(location -> location.getSubList().stream() .filter(this::correctTestDataValue) .collect(Collectors.toList())); So by now the sublist inside location doesnt change, which is obvious because stream and collect do create a new list, which...

java 8 fuction invocation

I have been using Java 8 from last couple of months and trying to get my head around lambdas. I have a quite bit understanding about concert. But struggling with custom functional interface execution as lambda call. If I create java Bifuctional interface implementation BiFunction<t1,t2,R> trade = (t1, t2) ->...

Java8 LocalDateTime to XMLGregorianCalender Remove “+05:30” Portion

Did like below, LocalDateTime currentUTCTime ="UTC")); String reqPattern = currentUTCTime.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss:SSS")); System.out.println("Required pattern: " + reqPattern); GregorianCalendar calendar = GregorianCalendar.from(currentUTCTime.atZone(ZoneId.systemDefault())); XMLGregorianCalendar xcal = DatatypeFactory.newInstance().newXMLGregorianCalendar(calendar); System.out.println("But Showing As :" + xcal); I want the output as 2015-06-18 11:59:15:135, but when i set the...

List elements disappeared when I used a lambda expression or assignment

I'm just trying to figure out what is happening in this python code. I was trying to use this answer here, and so I was tinkering with the console and my list elements just vanished. What I was doing was loading the lines into a file into a list, then...

java 8 stream groupingBy sum of composite variable

I have a class Something which contains a instance variable Anything. class Anything { private final int id; private final int noThings; public Anything(int id, int noThings) { = id; this.noThings = noThings; } } class Something { private final int parentId; private final List<Anything> anythings; private int getParentId()...

How to call a lambda using LINQ expression trees in C# / .NET

I want to use expression trees to dynamically create a method to call a lambda. The following code runs fine for the first call to the ComposeLambda function, but the second call fails with the following error message. Incorrect number of arguments supplied for call to method 'Int32 lambda_method(System.Runtime.CompilerServices.Closure, Int32)'...

How to convert single element list to java 8 optional

How to nicely convert list containing one or zero elements to Optional? The ugly code: List<Integer> integers = new ArrayList<>(); Optional<Integer> optional = integers.size() == 0 ? Optional.empty() : Optional.of(integers.get(0)); ...

Java 8 Optional.ifPresent is my code wrong or is it eclipse?

I am new to Java 8 and trying out Null type annotations and Optional. For my example below, I have used String rather than my class and am calling toUpperCase just to call something, in my case I actually call a function passing in a parameter (so don't think I...

Merging two List of objects in java 8

Let's consider a java class Parent with Parent with 20 attributes (attrib1, attrib2 .. attrib20) and its corresponding getters and setters. List<Parent> list1 contains n Parent objects Parent objects. List<Parent> list2 contains n Parent objects Parent objects. Now I want to merge two list and avoid duplicate objects based on...

Mapping a list to Map Java 8 stream and groupingBy

I have this simple Bean class: public class Book { public Book(Map<String, String> attribute) { super(); this.attribute = attribute; } //key is isbn, val is author private Map<String, String> attribute; public Map<String, String> getAttribute() { return attribute; } public void setAttribute(Map<String, String> attribute) { this.attribute = attribute; } } In...

Eclipse Kepler is unable to set the Java jdk 1.8 when maven project is updated

Installed java version is 1.8, while selecting this version in pom.xml and updating the maven project,it automatically jumps from 1.8 to 1.4, due to which I am unable to have Lambda expression specific code. I am using eclipse kepler. Any idea what is happening here ?...

How to sort HashMap in java depending on the size of value List

I have a hashmap like the following HashMap<String, ArrayList<String>> map=new HashMap<String, ArrayList<String>>(); map.put("USA", Arrays.asList("CA","IA","IL")); map.put("India", Arrays.asList("MUM","CAL")); map.put("Canada", Arrays.asList("TOR")); I want to sort the map depending on the size of the list in the value in ascending order.How can i do that. Is there any nice method to do so?...

Convert time based on timezone using java.time

How to change the time based on timezone in LocalDateTime, here i have built a date with Time zone as EST, now i need to find the UTC of the corresponding time. please help me how to solve this String str = "16Jun2015_153556"; DateTimeFormatter formatter = DateTimeFormatter.ofPattern("ddMMMyyyy_HHmmss"); formatter.withZone(ZoneId.of("EST5EDT")); LocalDateTime dateTime...

“CLR detected an Invalid Program” when compiling a constructor for List

I'm running into a strange problem when compiling a lambda expression for a parameterless constructor into a delegate. It works for almost all types that I have tried. Only the List<> is producing a “CLR detected an Invalid Program”. A Collection<> or an inherited class from List<> would not present...

Java 8 - return List (keyset) opposed to List>

I am trying to use java 8 to return me a list of key values(Integers) in which the value (Checkbox) is checked. The map I am trying to process is of the following form. Map<Integer, CheckBox> The aim is to return the key set for all values where the check...

Transforming a two-variable std::function to a single-variable one

I have a function which gets two values, x and y, and returns the result: std::function< double( double, double ) > mult = []( double x, double y){ return x*y; }; Now I want to get a single-variable function for a constant y. I have written the following code, but...

C# lambda expressions without variable / parameter declaration?

What's it called when a method that takes a lambda expression as the parameter, such as Enumerable.Where, is invoked without actually declaring a variable or method parameter in the expression? For example, I'm familiar with this lambda expression syntax: public string GetDigits(string input) { return new String(input.Where(i => Char.IsDigit(i)).ToArray()); }...

Java 8 - Difference between Optional.flatmap and

What's the difference between these to methods: Optional.flatMap() and An example would be appreciated....

Casting a list of objects to another one

I have the following classes(entities): Entity(base class, has 3 props) & Category(derives from Entity and adds some other props) The problem occurs when I read data from the DB(the fill method returns a list of Entities) and the compiler doesn't allow me to cast from Entity to Category. The problematic...

Play! Framework support for Java 8 Optional

I've got a Play! 2 routes file and controller that looks something like this: GET /books BooksController.getBooks(author: play.libs.F.Option[String]) public class BooksController extends Controller { public static Result getBooks(play.libs.F.Option<String> author) { ... } } I would like to refactor it to use Java 8's Optional, but this causes a compilation error:...

Select the first object that match condition or an inner object

I have a class that contains an inner list of the same class, For example: class Foo { string SearchId; List<Foo> GroupedPackages } I want to return the first "foo" instance that fits a condition, it can be in the main instance or in the inner List. This is what...

converting List type with Lambda Java

If I have an expression: / List<Long> / / List<String> / s.getPhones().addAll(Arrays.asList(rs.getString("phones").split(","))); Can I use Java Lambda to convert types with Long.parseLong in pritty form without "for loop" ? Or even if will use for loop, it will became more "codeless". How it must look like?...

linq max inside a “where” clause with an “and” condition too in lambda

I need to get a field with those conditions, my actual code in SQL is this: SELECT archivo, fechadiario FROM ri_diariodefotos WHERE [email protected] AND fechadiario = (SELECT MAX(fechadiario) FROM ri_diariodefotos WHERE [email protected]) I actually have this : RI_DiariodeFotos.Where(a=> a.Idproyecto == PROJECTID && a.Fechadiario == RI_DiariodeFotos .Where(x=> x.Idproyecto == PROJECTID) .OrderByDescending(x=>...

Passing method as a parameter - Is this possible?

I am trying to migrate to java 8 and have a number of methods in my dao classes which do the following @Override @SuppressWarnings("unchecked") public List<Group> getGroups() { Session session = sessionFactory.openSession(); List<Group> allGroups = (List<Group>)session.createQuery("from Group").list(); session.close(); return allGroups; } Here the same boiler plate and session.close is...

How can I simulate a nested function without lambda expressions in C++11?

I have the following code: int main(int argc, char **argv) { App app(800, 600); app.add_event_scene(Scene("Event Plot", event_plot)); Image x("sample.png"); struct foo { static void visual_plot() { x.draw(); } }; // Error. app.add_visual_scene(Scene("Visual Plot", foo::visual_plot));; return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Maven error with Java 8

Getting an error with Maven and Java 8 (jdk1.8.0_45). This issue does not occur with Java 7. MCVE Create a sample maven project. For example: mvn archetype:create -DgroupId=testinovke -DartifactId=testinvoke Create the following content in the generated file package testinovke; import java.lang.invoke.MethodHandle; import java.lang.invoke.MethodHandles; import java.lang.invoke.MethodType; public class App {...

Java 8 map to only value type collection

I want to convert my Map <K,V> into only a Set <V>. I could not find any example anywhere, including Oracle's documentation here: All I could go further is: myMap.entrySet().parallelStream(). filter((entry) -> entry.getKey().startsWith("a")) .collect(Collectors.toSet()); This returns a Set of Map.Entry. In this example it's Map<String, String> so I would...

Expression Lambda with types known at runtime

I am trying to make some Expressions where I will be using a lambda to create two methods: a selector and condition. Simplified the usage is condition(selector(data)), but the intemediate type is only known at runtime. I have the following code which works as long as the intemediate type is...

How to compose two lambdas of type “delegate” in c#

Lets assume we have defined two Lambdas. Func<TInput, TOutput> a = …; Func<TInput1, TInput2, TOutput> b = …; Now lets assume that we have some code that does not work with generics and receives these Lambdas as not further typed delegates. delegate da = a; delegate db = b; In...

How To Calculate The Number Of Days In A Period

For the following Period calculation: Period.between(LocalDate.of(2015,8,1), LocalDate.of(2015,9,2)) the result is: P1M1D This is equivalent to 31 days + 1 day = 32 days. For this Period: Period.between(LocalDate.of(2015,8,1), LocalDate.of(2015,10,2)) the result is : P2M1D This is equivalent to: 31 days (in August) + 30 days (in September) + 1 (in October)...

Why is generic of a return type erased when there is an unchecked conversion of a method parameter in Java 8?

Consider the following code sample: import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List list = new ArrayList<Integer>(); String response = getProducer(list).get(); } static Producer<String> getProducer(List<Integer> list) { return new Producer<String>(); } } class Producer<T> { T get() { return null; } } When...

Creating an Expression that returns an object

I have this method: public R TranslateExpression<R>(Expression exp) where R : DbRequest { //... } In another class I have the following method: public void Persist(E entity) { Expression expr = Expression.Return(entity); //Does not compile, but I'm looking for something like this PersistRequest request = TranslateExpression<PersistRequest>(expr); } How can I...

Dividing an Expression in C# using Expression.AndAlso() causes an Exception

On my project written in C#, I've found a HUGE predicate that is used in this method of linq : public static IQueryable<TSource> Where<TSource>(this IQueryable<TSource> source, Expression<Func<TSource, bool>> predicate); this predicate works perfectly, but it as so much condition that I struggled a lot before understanding it. I would like...

State in a java.util.function.Function

Suppose that I have a class which implements java.util.function.Function. The Function needs to know about a start date and end date but these will be constant throughout the lifetime of the function. I'm considering implementing the Function with private final fields for the start and end dates, as the apply...

How do I mock multiple levels of DbSet.Include lambdas?

I'm using Moq to write unit tests that use Entity Framework 6 DbSet and DbContext objects. I have a service method with a cascading/multi-level Include and I can't figure out how to set it up for testing. The service method looks something like this: return DataContext.Cars .Include(p => p.Model) .Include(p...

How to use lambda expression to call the comparator?

I am doing the leetcode's largest Number problem. Here is the problem: Given a list of non negative integers, arrange them such that they form the largest number. For example, given [3, 30, 34, 5, 9], the largest formed number is 9534330. and there is a 5 lines C# code:...

Java8 LocalDate Time Adding Hours Not Wroking

I tried like below, but in both the cases it is showing same time? What i am doing wrong. LocalDateTime currentTime ="UTC")); Instant instant = currentTime.toInstant(ZoneOffset.UTC); Date currentDate = Date.from(instant); System.out.println("Current Date = " + currentDate); currentTime.plusHours(12); Instant instant2 = currentTime.toInstant(ZoneOffset.UTC); Date expiryDate = Date.from(instant2); System.out.println("After 12 Hours =...

How to delete a row from database using lambda linq?

I want to perform a delete operation to unfriend a user in a certain android application I'm developing. The following method returns "Done" but the data doesn't delete from the table. What is the problem here? public string deleteFriend(int user, int friend) { int i = db.Friends.Where(x => x.Person.Id ==...

Why I'm getting different java versions

I just upgraded my Java from 1.8 update 31 to update 45. Once done, I checked in the Java Console it shows Java 8 update 45. But, when I checked in the terminal it shows java version "1.8.0_31". I checked using Verify Java Version, and it show You have the...

How best to prevent unused variable warnings in custom assert without sizeof?

Based on advice in I've been working with my own version of assert (called emp_assert) for a while now. As such, when NDEBUG is set, my assert looks like: #define emp_assert(EXPR) ((void) sizeof(EXPR) ) This definition assures that any variables in EXPR still count as "used" in the compiler,...

Dynamic lambda wrapped with try catch

I want to filter an IEnumerable<ModuleItem> by an Where calls defined by the user (so the expression is given by a String object) So far I am able to create my filters with DynamicLinq with this code Expression<Func<ModuleItem, bool>> expr = System.Linq.Dynamic.DynamicExpression.ParseLambda<ModuleItem, bool>(value, null); The problem is that the overall...