FAQ Database Discussion Community


How can I suppress anonymous new runnable() can be replaced with lambda

java,android,lambda,java-8
I got "anonymous new runnable() can be replaced with lambda" warning with the following code. final ScrollView sv = (ScrollView) findViewById(R.id.scrollView); sv.post(new Runnable() { @Override public void run() { sv.fullScroll(ScrollView.FOCUS_DOWN); } }); I searched on Google very hard and seems to be re-write using lambda expression... final ScrollView sv =...

Java 8 Lambda for Anonymous Class

java,lambda,anonymous-class
I have a tricky situation here, which I would like to optimize from the code perspective. Is there any way to shorten the following method via Lambda / Java8 expressions? // total amount of audiences registry.register("metric.persons.total", new CachedGauge<Integer>(1,TimeUnit.MINUTES) { @Override protected Integer loadValue() { return personService.findAll().size(); } }); The CachedGauge...

converting List type with Lambda Java

java,lambda
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?...

Share variable between two lambdas

c++,lambda,anonymous-function,capture
I want to be able to share a variable in the containing scope between two lambda functions. I have the following: void holdAdd(const Rect& rectangle, Hold anonymousHeld, Hold anonymousFinish) { std::map<int,bool> identifierCollection; HoldFinish holdFinish = [=](const int& identifier) mutable { if (identifierCollection.count(identifier) == 0) return; identifierCollection.erase(identifier); anonymousFinish(); }; holdCollisionCollection.push_back([=](const int&...

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

c#,.net,linq,lambda,expression-trees
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)'...

What is the difference between these constructs such that one won't compile?

java,lambda,compilation,java-8
A little backstory (ok, a lot): I've been working on creating classes that take java.util.function types and wrap their execution with try/catch blocks to remove the need for using try/catch from within lambda statements. Something that would allow this test code: list.forEach(ExceptionWrapper.wrapConsumer(s -> {throw new Exception(s);})); In doing so, I...

Dynamic lambda wrapped with try catch

c#,linq,dynamic,lambda
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...

Understanding Move Capture in Lambdas for C++11

c++,c++11,lambda,move,rvalue-reference
I have a question regarding the workaround proposed in order to address move capture in C++11 lambdas. In particular, taking the example from Meyer's book: std::vector<double> data; ... auto func = std::bind( [](const std::vector<double>& data) { /*uses of data*/ }, std::move(data) ); My question is: what would be the consequences/meaning...

C++ lambda, not seeing function and argument?

c++,multithreading,c++11,lambda,boost-asio
I have some code using a wrapper class around std::thread, which is using a timer struct (based upon boost::asio), to call methodToCallEachIteration() every 5000 milliseconds: class OurThreadWrapperClass{ OurThreadWrapperClass(boost::asio::io_service& = generic_timer_queue_s()); }; class A { A() : thread1(_TimerIOService){ thread1.setInterval(5000); // This sets the callback function, to be called every INTERVAL ms....

Java 8 : Lambda Function and Generic Wildcards

java,lambda,java-8
I have the following class class Book implement Borrowable { @Override public String toString(Function<? extends Borrowable , String> format) { return format.apply(this); } } This gives me an error that i cannot use "apply" on this(Book object). My current formatter is Function<Book, String> REGULAR_FORMAT = book -> "name='" + book.name...

How to calculate differences in a list of integers using lambda expressions

java,lambda,stream
Lets say I have the following array: {1,2,3,4,6,7,8} which is put in a Stream<Integer> s = Stream.of(1,2,3,4,6,7,8); How can I use in Java lambda expressions and Stream functions to calculate the difference between each element and the next (in this case {1,1,1,2,1,1})? This is not really a reduce operation as...

TypeScript: Lambdas and using 'this'

lambda,typescript,this
JavaScript frameworks often call callbacks using apply(). TypeScript's arrow notation, however, doesn't seem to allow me to access the 'this' pointer. How's it done? If it isn't, is there a place to down-vote the current 'this' handling on Lambdas?...

Is there a better way to do this than writing a wrapper allocator that stores a reference to a stateful allocator object?

c++,memory-management,lambda,allocator,std-function
For example: struct Foo { MyPoolAlloc<char> pool; std::vector<int , MyPoolAlloc<char>> vec_int; // The wrapper allocator would replace MyPoolAlloc<> here. std::vector<std::function<void()> , MyPoolAlloc<char>> vec_funcs; // The wrapper allocator would replace MyPoolAlloc<> here. Foo() : vec_int(pool) , vec_funcs(pool) {} // I want to store lambdas with captured variables using the custom allocator...

java 8 fuction invocation

java,lambda,functional-interface
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) ->...

Apply a list of Functions to a Java stream's .map() method

java,lambda,functional-programming,java-8,java-stream
I map a stream of NameValuePairs with a lookupFunction (which returns a Function), like this: List<NameValuePair> paramPairs = getParamPairs(); List<NameValuePair> newParamPairs = paramPairs.stream() .map((NameValuePair nvp) -> lookupFunction(nvp.getName()).apply(nvp)) .flatMap(Collection::stream) .collect(toList()); But what if lookupFunction returned a Collection<Function> instead, and I wanted to perform a .map() with each of the returned Functions....

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

java,lambda,java-8
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()) {...

Java 8 map to only value type collection

java,lambda,java-8,collectors
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: https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html 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...

Remove last “X” characters from string [duplicate]

c#,regex,lambda
This question already has an answer here: How to remove the last comma and space from string (if there) using regex? 4 answers I have a string that can end will several "X" characters. Let's say the string ends in commas like this. string X = "1,2,3,,,"; I need...

LINQ Lambda Left join with an Inner join

c#,linq,lambda
I have written a LINQ lambda query which so far which returns all staff which do not have an associated training row which works fine. I now need to amend my where clause to use the manager id joining manager table onto staff. I am a little unsure how to...

How to check if Collection is not empty using java Stream

java,lambda,stream,java-8
I am new to Java 8. I am not able to understand what is wrong in the following piece of code. The idea is to sent Collection if its not empty . But if the collection is empty than sent HttpStatus.NOT_FOUND Entity response. @RequestMapping(value = "/find/pks", method = RequestMethod.GET, produces...

Expression Lambda with types known at runtime

c#,lambda,expression-trees
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...

Explain this python lambda

python,django,lambda
I am implementing a monthly calendar in django and used some code I found online. Within the code there is a lambda function that I need to tune for my specific use. def group_by_day(self, event): field = lambda event: event.start.day return dict( [(day, list(items)) for day , items in groupby(event,...

Dynamic where expression to use in linq

c#,lambda,delegates
I want to build a dynamic where expression to use over a list of objects. var list = new List<Dummy>(); IQueryable<Dummy> queryableData = list.AsQueryable<Dummy>(); MethodCallExpression wherExpression = Expression.Call(typeof(Queryable), "Where", new Type[] { typeof(Dummy) }, queryableData.Expression, Expression.Lambda<Func<Dummy, bool>>(lambda.Body, lambda.Parameters.First())); Update: lambda.Body lambda.Body = {(((x.Title.Contains("Mihai") Or x.Description.Contains("Mihai")) Or x.Comments.Contains("Mihai")) Or...

C# lambda expressions without variable / parameter declaration?

c#,.net,linq,lambda
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()); }...

OrElseGet chaining in Java8

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....

Lambda Metafactory Variable Capture

java,lambda,java-8
When creating a lambda manually using MethodHandles.Lookup, MethodHandles, MethodTypes, etc, how might one implement variable capture? For example, with no capture: public IntSupplier foo() { return this::fortyTwo; } /** * Would not normally be virtual, but oh well. */ public int fortyTwo() { return 42; } and its clunkier form,...

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

c++,c++11,lambda,assert,sizeof
Based on advice in http://cnicholson.net/2009/02/stupid-c-tricks-adventures-in-assert/ 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,...

Creating an Expression that returns an object

c#,.net,lambda,expression
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...

variable '' of type '' referenced from scope '', but it is not defined

c#,lambda,expression
Well, the following code is self-explaining; I want to combine two expressions into one using And operator. The last line causes rune-time the error: Additional information: variable 'y' of type 'System.String' referenced from scope '', but it is not defined Expression<Func<string, bool>> e1 = y => y.Length < 100; Expression<Func<string,...

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

c++,function,c++11,lambda,allegro
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)); app.run(); return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Extend a lambda expression

c#,lambda
I have a existing lambda-expression which was created like: Expression<Func<Entities.Area, bool>> where = (x => (x.Created > this.Value || (x.Changed != null && x.Changed > this.Value))); Now, I have to extend this expression with this one: Expression<Func<Entities.Area, bool>> whereAdd = (x => x.Client.Id == ClientInfo.CurrentClient.Id); The Result should be like:...

Declaring a Ruby lambda with a yield

ruby,lambda,functional-programming
I'm writing a method that splits an array of struct into a couple of different, arrays while also eliminating elements with nil values. What I want to write is: def my_func(some_data) f = lambda{|data| data.select{|m| yield(m).present? }.map { |m| [m.date, yield(m)]}} x = f.call(some_data) {|m| m.first_var} y = f.call(some_data) {|m|...

Getting coefficient at best lambda in glmnet in R

r,lambda,regression,glmnet
I am using following code with glmnet: > library(glmnet) > fit = glmnet(as.matrix(mtcars[-1]), mtcars[,1]) > plot(fit, xvar='lambda') However, I want to print out the coefficients at best Lambda, like it is done in ridge regression. I see following structure of fit: > str(fit) List of 12 $ a0 : Named...

Lambda Expression Parameters/declaration

java,function,math,lambda,expression
I have been signed up for a while and don't usually post unless I really cannot find an answer, and now, I feel quite stuck. I have only recently started getting familiarized with java Lambda expressions (mainly the function ones) such as BinaryOperator and Bifunction..) I was looking at the...

Listener can be replaced with lambda

android,lambda,alertdialog,android-alertdialog,autosuggest
I have implemented an AlertDialog with normal negative and positive button click listeners. When I called new DialogInterface.OnClickListener() it was showing me a suggestion saying: Anonymous new DialogInterface.OnClickListener() can be replaced with lambda. I know it's not an error or something big but what exactly is this suggestion and what...

How to apply a function to the elements of a pandas dataframe

pandas,lambda,dataframes
I want to apply a lambda function to the elements of a dataframe, in the same way as np.sqrt returns a dataframe with the sqrt of each element. However pd.DataFrame.apply apply the function to an row or an column. Is there a similar comand that apply a lambda function on...

Perform Calculations Within List Using Linq and Lambda Expressions

c#,linq,lambda
I have the following object: public class Foo { public Int32 Id public Int32 SampleId public Int32 CompanyId public Decimal Data } public class Bar { public Int32 CompanyId public Decimal Data } I have a list of these objects. I want to perform a calculation where I group the...

List elements disappeared when I used a lambda expression or assignment

python,lambda
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...

State in a java.util.function.Function

lambda,java-8,java-stream
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...

Group collections on the basis of Id using linq

c#,linq,lambda
I have a three different collections named as Collection1,Collection2,Collection3. Now I want to group them up by their Id's also want to order that Id's on the basis of max count of them . The third thing that I want is to add that value to a Icollection . I...

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

c#,jquery,asp.net-mvc-4,lambda
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();...

Using Lambda in Python with a Dictionary

python,lambda
Yesterday I asked a question about using a dictionary and lambda, Yesterdays question, however I still can't get this to work, see code below, lookupDictionary = input() dictionaryTest = { lambda : file1.write(variableTowrite) } dictionaryTest.get(lookupDictionary) Any help?...

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

c#,.net,generics,lambda
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...

Functional Interface Inheritance Quirk

java,lambda,java-8,default-method,functional-interface
I have a custom interface I've been using for some time that looks something like this: public interface Function<T, R> { R call(T input); } I'd like to retrofit this interface with both Java's Function as well as Guava's Function, while keeping it a FunctionalInterface. I thought I had the...

Aggregating lambda functions in pandas and numpy

python,numpy,pandas,lambda
I have an aggregation statement below: data = data.groupby(['type', 'status', 'name']).agg({'one' : np.mean, 'two' : lambda value: 100* ((value>32).sum() / reading.mean()), 'test2': lambda value: 100* ((value > 45).sum() / value.mean())}) I continue to get key errors. I have been able to make it work for one lambda function but not...

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

c#,linq,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=>...

What is the point of being able to use compile-time characteristics of non-captured local variables in a lambda?

c++,c++11,lambda,capture
I noticed that one is allowed to use compile-time characteristics of variables which were not captured in lambda e.g. call sizeof, decltype functions, for example: #include <iostream> void f () { } int main() { int y = 13; auto x = []{ return sizeof (decltype (y));}; std::cout << x...

Seperate List using LINQ

c#,linq,lambda
I have a List of Object with the following properties public class Class1 { public Int64 Id { get; set; } public Decimal? Amt { get; set; } } I am creating a list of Object with the above properties List<Class1> n = new List<Class1>(); Class1 a = new Class1();...

Syntax error while using Lambda functions

python,filter,lambda
I have a list with some dummy email address as below: listEmails = ['[email protected]', '[email protected]', '[email protected]'] I was trying to use lambda and filter to get the list of valid email address. let's assume [email protected] is the only invalid email address. I used the regular expression to filter out the...

How to write inline lambda expression for a specific signature

c#,lambda
This is making my brain melt. Given these signatures of IApplicationBuilder how do I write a lambda expression that satisfies the extension method? public IApplicationBuilder Use(Func<RequestDelegate, RequestDelegate> middleware) Extension method: (I want to satisfy this extension) public static IApplicationBuilder Use(this IApplicationBuilder app, Func<HttpContext, Func<Task>, Task> middleware) This is what I...

Seperate lambda query into new method

c#,lambda
Below is two class I writed: class a { public void getEntities(){ B b = new b(); List<entity> entities = b.select(c=>c.id==5); // more detail } } class b { public List<entity> Select( LambdaExpression expression){ return _dbSet.where(expression).ToList(); } } But system tell me the LambdaExpression expressionis invalid. Now how can I...

Nested maps in Python 3

python,python-3.x,lambda
I want to transform my list list = [" a , 1 ", " b , 2 "] into a nested list [["a","1"],["b","2"]]. The following works: f1_a = map(lambda x :[t.strip() for t in x.split(',',1)],list) but this does not work with Python 3 (it does work with Python 2.7!): f1_b...

How to properly merge lambda-expressions with different parameters

c#,lambda,expression
I have two expressions : Expression<Func<long, bool>> condition = x => x < max; // Exp # 1 if (count > 0) { Expression<Func<int, bool>> limit = x => x > -1; // Exp # 2 condition = Expression.Lambda<Func<long, bool>>( Expression.AndAlso(condition, limit), condition.Parameters); } var comparator = condition.Compile(); while (comparator(k++,...

Which dynamically created object called the function?

python,lambda,tkinter
I am making a python app with a Tkinter GUI. So far it has some dynamically created listboxes which I will link all to one scrollbar. I need a way to let yscroll() know which listbox has been scrolled. Passing the i variable to yscroll() does not work. from Tkinter...

Lambda expressions in Java 8

java,lambda
I want to generate a list of numbers using lambda expressions and not a for-loop. So let's say I want to generate a list of all triangular numbers under 100. Triangular numbers are numbers which follow the formula: (n*n+n)/2 What is the best way of doing this? Currently I have...

How do I change the context of lambda?

ruby,lambda,metaprogramming
If you run the code below you get an error. class C def self.filter_clause param_1 puts param_1 yield # context of this param is class B end def hi "hello" end end class B def self.filter(value, lambda) code = lambda { filter_clause(value, &lambda) } C.instance_exec(&code) end filter(:name, ->{ hi })...

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

entity-framework,unit-testing,lambda,moq
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...

Java 8 lambdas nested Map

java,lambda,java-8,java-stream,collectors
I am trying to use Java-8 lambdas to solve the following problem: Given a List<Transaction>, for each Category.minorCategory I require the sum of Transaction.amount per Category.minorCategory and a Map of Transaction.accountNumber with the sum of Transaction.amount per Transaction.accountNumber. I have this working, as per the code below. I now have...

Java 8 Stream operation

java,lambda,java-8,java-stream
Let's say I have a Stream of Strings called s. Is it possible to have a unary operation that converts every lone String to two Strings? So if the original Stream contains {a,b,c} and the operation converts every single String s to s + "1" and s + "2" then...

Why this anonymous method does not work while the lambda does?

c#,lambda,anonymous-function
I am learning anonymous methods, lambdas etc. and cannot find the reason why it does not work here: // this does not work MyDictionary.Keys.Where(delegate(string s) { s.Length == 5; }); // this works MyDictionary.Keys.Where(w => w.Length == 5); ...

How do I remove items from generic list, based on multiple conditions and using linq

c#,linq,list,lambda
I have two lists, one containing urls and another, containing all MIME file extensions. I want to remove from the first list all urls that point to such files. Sample code: List<string> urls = new List<string>(); urls.Add("http://stackoverflow.com/questions/ask"); urls.Add("http://stackoverflow.com/questions/dir/some.pdf"); urls.Add("http://stackoverflow.com/questions/dir/some.doc"); //total items in the second list are 190 List<string> mime =...

Why do you need lambda to nest defaultdict?

python,lambda,defaultdict
I am a bit confused on why you need a lambda function for nesting defaultdict Why can't you do it like this? test = defaultdict(defaultdict(list)) instead of test = defaultdict(lambda:defaultdict(float)) ...

How to capture type of a local variable inside a lamda expression in linq

c#,linq,lambda,closures,abstract-class
I found some duplicate code today and would like to reduce it to one method. In order to do it, I'd like to inject something more abstract into the lambda here: public IEnumerable<AbstractFoo> GetMatchingFoos() { return IEnumerable<AbstractFoo> exactMatchFoo = exactMatchList .Where (d => d is RedFoo); } //Horrifying duplicate code!:...

How to delete a row from database using lambda linq?

c#,android,linq,lambda
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 ==...

Implement method for class in a different class

java,interface,lambda
There is a class A which has an undefined method called OnEvent. I want this method to be define by the class that instantiates a class A Object. Like this: public class A{ int someVar=1; float anotherVar=2; public void method1(){ ... if( event ) OnEvent(); ... } //OnEvent is not...

Instance of Show for Lambda

haskell,lambda,instance,show,typeclass
So, I have already defined the lambda data type as such: data LExpr = Variable String -- variable | Apply LExpr LExpr -- function application | Lambda String LExpr -- Lambda abstraction deriving (Eq, Show) Now I want to implement an instance of Show myself. I have already the function...

Trying to use lambda for the first time and the code doesn't compile [closed]

eclipse,lambda,java-8
I trying to use the lambda expressions in Java-8 using eclipse IDE. I took this example from some youtube tutorial which worked well there, but in my code it doesn't and it gave me this error. I tried to add Integer before the value and it still the same. How...

Java 8 - Call interface's default method with double colon syntax

java,inheritance,lambda,java-8
I'm delving into the Java 8 innovations, and I'm trying to call a default method which I implement in a high-level interface, even when a subclass overrides it. I would have no problem going back to implementing a Comparator in my BusinessLogic class, but I was wondering if there's some...

converting list of object to array in c# - what does the “x => x.Name” syntax mean? [duplicate]

c#,arrays,lambda
This question already has an answer here: C# Lambda expressions: Why should I use them? 12 answers I was looking for a solution to convert each object's properties on a List to some arrays when finally I found this Then I found this code MyList.Select(x=>x.Name).ToArray(); which is the solution...

Java 8 stream unpredictable performance drop with no obvious reason

java,performance,lambda,java-stream,jmh
I am using Java 8 streams to iterate over a list with sublists. The outer list size varies between 100 to 1000 (different test runs) and the inner list size is always 5. There are 2 benchmark runs which show unexpected performance deviations. package benchmark; import org.openjdk.jmh.annotations.*; import org.openjdk.jmh.infra.Blackhole; import...

How should I be using LambdaMetaFactory in my use case?

java,reflection,lambda,java-8
Despite having read all the documentation I'm aware of, I cannot resolve an issue with using lambdas to execute a method. To give a bit of background my use case is a plugin system. I'm using an annotation (@EventHandle) which can be assigned to any method. I use reflection and...

Calling a stateless lambda without an instance (only type)

c++,c++11,lambda,variadic-templates,template-meta-programming
I'm trying to write a wrapper for a "register callback" type of interface from a C library. The issue is quite complicated by the fact that, the library lets you register "variadic" functions by accepting a list of parameter definitions. Then at callback time, the function is expected to extract...

Select the first object that match condition or an inner object

c#,lambda,ienumerable
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...

Mapping a vector of one type to another using lambda

c++,c++11,lambda,functional-programming
I have a bit of code that looks like B Convert(const A& a) { B b; // implementation omitted. return b; } vector<B> Convert(const vector<A>& to_convert) { vector<B> ret; for (const A& a : to_convert) { ret.push_back(Convert(a)); } retun ret; } I was trying to rewrite this using lambdas but...

Check for Null in an Expression

c#,lambda,expression-trees
I have an Expression that looks like this: obj => obj.Child.Name where Name is a string. What I want to do is get the value of Name. I can get it just fine by compiling the method and invoking it, however a NullReferenceException is thrown if Child is null. Is...

Is there a way to see the body of a lambda in Racket?

lambda,scheme,racket
Say I have this code: #lang racket (define a ((λ (x) x) ((λ (y) y) (λ (z) ((λ (w) w) z))))) I know intuitively that this lambda expression is (extensionally) equal to (λ (z) z) My question is if there is a way to print out the body of a...

Why do we need to avoid mutation while coding? What is mutation?

java,lambda,stream,mutation
Why the second part of the code (with the stream) is a better solution compared to first? First : public static void main(String [] args) { List<Integer> values = Arrays.asList(1,2,3,4,5,6); int total = 0; for(int e : values) { total += e * 2; } Secound : System.out.println(total); System.out.println( values.stream()...

Java 8 Lambda expressions for solving fibonacci (non recursive way)

java,lambda,functional-programming,java-8
I am a beginner in using Lambda expression feature in Java 8. Lambda expressions are pretty well useful in solving programs like Prime number check, factorial etc. However can they be utilized effectively in solving problems like Fibonacci where the current value depends on sum of previous two values. I...

Java 8 Consumer/Function Lambda Ambiguity

java,lambda,java-8,method-overloading,jls
I have an overloaded method that takes a Consumer and a Function object respectively and returns a generic type that matches the corresponding Consumer/Function. I thought this would be fine, but when I try to call either method with a lambda expression I get an error indicating the reference to...

How do I filter a collection by type?

c#,lambda,where-clause
I have three classes: public class class1 {} public class class2 : class1 {} public class class3 : class1 {} and a list of items of class1, but I want to get only the ones of type class2, something like: list = list.where(x=>x.classType == class2) how is the proper way...

What is the difference between a lambda and a method reference at a runtime level

java,serialization,lambda,java-8
I've experienced a problem that was happening using a method reference but not with lambdas. That code was the following : (Comparator<ObjectNode> & Serializable) SOME_COMPARATOR::compare or, with lambda, (Comparator<ObjectNode> & Serializable) (a,b) -> SOME_COMPARATOR.compare(a,b) Semantically, it is strictly the same, but in practice it is different as in the first...

Looping though collection inside other collection and LINQ lambda expression

c#,linq,lambda
Here I'm selecting descriptions from all FactoryOption with an Header of "TRANSMISSION" transmissionFromOptions = _vehicleDetails.factoryOption .Where(x => (x.header != null && x.header.Value.ToUpper() == "TRANSMISSION")) .Select(x => x.description) .SelectMany(x => x); If the header is null I would like to search for the header in ambiguous options which matches to "TRANSMISSION"...

More pythonic/elegant way to do this Python string slicing?

python,string,lambda
So I have a function that takes two string inputs - it slices them so that if of even length, the length of the front segment is the same as that of the back, and if of odd length, the middle character goes to the front segment (i.e. hello ->...

How to use lambda expression to call the comparator?

java,lambda,java-8
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:...

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

c#,.net,linq,lambda,clr
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...

Mapping a list to Map Java 8 stream and groupingBy

java,collections,lambda,java-8
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...

Sorted(items, lambda) with multiple items, one reversed

python,string,list,sorting,lambda
How would I do the following sort? import re list_of_strings=['hulu_delta_20150528.xml', 'hulu_delta_20150524', 'playstation_full_20150529', 'hulu_full_20150528.xml'] sorted(list_of_strings, key=lambda x: ( x[:3], re.search(r'\d{8}',x).group() if re.search(r'\d{8}',x) else None, -x # How would this be done as a third criteria? )) Specially, how would I sort the item by reverse alphabetical as the third criteria? The...

operators in predicate as argument in lambda expression

java,lambda,type-conversion,java-8,predicate
I need to use Predicate as argument in lambda expression. I tried an example code but seeing compiler error. I see that the compiler is treating the same Predicate differently for different arguments. So Predicate arguments n -> true and n -> false works but n -> n%4 == 0...

Defining cons, car and cdr with lambda - how does it work? [duplicate]

lambda,scheme,sicp,r5rs
This question already has an answer here: Use of lambda for cons/car/cdr definition in SICP 2 answers I can't seem to explain how this definition of cons, car and cdr works: (define (p-cons x y) (lambda (proc) (proc x y))) (define (p-car proc) (proc (lambda (p q) p))) (define...

Why does this lambda require *arg, what difference does it make?

python,lambda
I came across a pretty clever little function that takes two functions, applies one on top of each other given an argument x: def compose(f,g): return lambda *x: f(g(*x)) Now my issue is with *x, as I don't see it really doing anything here. Why couldn't it be simple x...

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

c++,c++11,lambda
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...

Java 8 extract first key from matching value in a Map

java,lambda,java-8
Suppose I have a map of given name, surname pairs and I want to find the given name of the first entry in that map that has the surname matching a certain value. How would we do this in a java 8 fashion. In my test case example below I...

construction of thread using lambda expression

multithreading,c++11,lambda,threadpool
Can somebody explain where a thread is created on the lambda function below? What is the technique used? Can somebody recommend a reference to understand the semantics? I posted the full code now: class ThreadPool { public: ThreadPool(size_t); template<class F, class... Args> auto enqueue(F&& f, Args&&... args) ->std::future<typename std::result_of<F(Args...)>::type>; ~ThreadPool();...

How to get unique id of lambda function for “do once” pattern?

c#,lambda,anonymous-function,uniqueidentifier,once
I want to implement "do once" pattern that allows me to avoid writing 3 things: declaring var first = true if(first) Do(...) statement inside repeated block of code first = false assignment inside repeated block of code I also want to avoid workarounds like these: manually maintaining and passing unique...

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

c#,linq,lambda,expression
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...

Casting a list of objects to another one

c#,linq,casting,lambda,dao
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...

commands in tkinter when to use lambda and callbacks

python,lambda,tkinter,command
I'm confused as to the difference between using a function in commands of tkinter items. say I have self.mb_BO.add_radiobutton(label= "Red", variable=self.BO, value=2, command=self.red) what is the difference in how the add statement works from this: self.mb_BO.add_radiobutton(label= "Red", variable=self.BO, value=2, command=self.red()) where func red(self) changes the color to red. And self.mb_BO.add_radiobutton(label=...

Data from SQL to be exported into CSV (New line issue), I use C# coding on export [duplicate]

c#,sql,sql-server,lambda,export-to-csv
This question is an exact duplicate of: SQL Query to Lambda C# 2 answers I have data that contains Char(13) and Char(10) on my database, upon exporting the data onto csv, some data on the last fields create a new line in which it wrecks the other rows. for...

Proper use of lambda in function definition

python,string,lambda,python-3.4
I want to write a simple function that recognizes palindromes: >>> def palindrome(s): return s == s[::-1] It works fine but it is case sensitive and to fix that I could do: >>> def palindrome(s): return s.lower() == s[::-1].lower() >>> palindrome('Aba') True but I figure it's not very elegant. I...

Lambda not equal on join

c#,.net,lambda,.net-4.5
Table 1 called Category contains 70 records Table 2 called FilterCategorys contains 0 records (currently). my lambda join, I want to pull only records that don't match, so in this case I expect to get 70 records back. Here's my incorrect Lambda: var filteredList = categorys .Join(filterCategorys, x => x.Id,...