Java 8 Optional orElse whereas isPresent [duplicate] - java-8

This question already has an answer here:
Java 8's orElse not working as expected
(1 answer)
Closed 6 years ago.
I am very confused about the orElse method of an optional.
I have used following code, which calls the orElse case every time although the optional value is present:
Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type);
NotificationSettings notificationSettings = ons.orElse(createNotificationSettings(profile, type));
If I rewrite the code to the following, the correct path (ifPresent) is chosen:
Optional<NotificationSettings> ons = userProfileDao.loadNotificationSettingsByTransportType(type);
NotificationSettings notificationSettings = ons.isPresent() ? ons.get() : createNotificationSettings(profile, type);
I thought the orElse is doing the same like my example in the second case. What am I missing?

To avoid evaluating the alternative value use orElseGet:
NotificationSettings notificationSettings =
ons.orElseGet(() -> createNotificationSettings(profile, type));
There's no magic. If you call a method like orElse, all its parameters get evaluated eagerly. orElseGet gets around it by receiving a Supplier to be evaluated lazily.

Related

Issue with creating a byte object [duplicate]

This question already has answers here:
how to put a backquote in a backquoted string?
(3 answers)
Closed 2 years ago.
I am trying to initialize a JSON object as a byte in go lang. Here, I am attaching two exmples
var countryRegionData = []byte(`{"name": "srinivas"}`)
var countryRegionData = []byte(`{"name": "srini`vas"}`)
In the first initilization there is no issue, all working as expected.
In the second initialization if you see there is ` between i and v. I have some requirement like this. How to achieve?
A backtick cannot appear in a raw string literal. You can write something like this:
var countryRegionData = []byte("{\"name\": \"srini`vas\"}")
You cannot use escaping in a raw string literal. Either you have to use double-quoted string:
"{\"name\": \"srini'vas\"}"
Or do something like:
`{"name": "srini`+"`"+"vas"}`

Java8 stream - how to get convert Set to List when .map() found a Set [duplicate]

This question already has answers here:
How can I turn a List of Lists into a List in Java 8?
(12 answers)
Closed 2 years ago.
I want to convert the result to List for the following code:
List<Task> taskList = projectMap.stream().map(p -> p.getProject().getTasks()).collect(Collector.toList());
but the problem is p.getProject().getTasks() is actually a Set, so I got this error
Type mismatch: cannot convert from List<Set<Task>> to List<Task>
So I also tried to return the result as a Set
Set<Task> taskList = (Set<Task>)projectMap.stream().map(p -> p.getProject().getTasks());
error
java.util.stream.ReferencePipeline$3 cannot be cast to java.util.Set
Is there anyway to convert the result to List ?
or remain the result as Set also fine, my goal is to get the list of Task which located in ProjectMap > Project > Task
Use flatMap:
List<Task> taskList = projectMap.stream()
.flatMap(p -> p.getProject().getTasks().stream())
.collect(Collector.toList());

Request only method returns original request array [duplicate]

This question already has answers here:
Laravel change input value
(7 answers)
Closed 3 years ago.
So I'm manipulating Request and setting an object to new value.
$assignable = ['seats'];
$request->seats = $this->myMethod($request->seats);
var_dump($request->seats); //works
$data = $request->only($assignable);
var_dump($data['seats']); // returns the initial value of 'seats' (without passing through $this->myMethod)
Now I know I could first convert the request object to array and then manipulate the '$data', but the above code is a sample and the real code is much more complicated, it would require to change the whole architecture to do that way.
Has anyone experienced anything like this?
Instead of this:
$request->seats = $this->myMethod($request->seats);
Try this:
$request->merge(['seats' => $this->myMethod($request->seats)]);

How to use variable for xml attribute value in vb 2015?

I wonted to know if i can use a variable in selecting node statement ex:
Pgs = xmldoc.SelectNodes("/* [#Id = 160578]")
I need to replace this 160578 number with a variable?
A naive (and prone to injection) is string manipulation e.g. xmlDoc.SelectNodes(String.Format("/*[#Id = {0}]", yourVariable)). The right approach would be to use the second argument to SelectNodes and implement variable resolution in an implementation of XsltContext https://msdn.microsoft.com/en-us/library/system.xml.xsl.xsltcontext(v=vs.110).aspx. The project https://mvpxml.codeplex.com/releases/view/4894 has a class DynamicContext doing that, although that project is done in C# you could of course compile it with VS and integrate the API into your VB code:
Dim idVar As Double = 160578
Dim dynContext As New DynamicContext
dynContext.AddVariable("id", idVar)
Pgs = xmldoc.SelectNodes("/*[#Id = $id]", dynContext)

Unable to assign instance_variable_get values to dynamic variable in ruby [duplicate]

This question already has answers here:
How to dynamically create a local variable?
(4 answers)
Closed 8 years ago.
Instance_variable_get value can be assigned to a variable as follows. The following code throws correct output
a = instance_variable_get("#" + "#{code}" + "_resource").get_price(a, b) // working
But unable to assign instance_variable_get value to a variable with dynamic param. Assume the code is a dynamic param which is in loop.
"#{code}_buy" = instance_variable_get("#" + "#{code}" + "_resource").get_price(a, b) //Not working
The above method throws the following error
syntax error, unexpected '=', expecting keyword_end
You could use a hash instead:
hash = {}
hash["#{code}_buy"] = some_value

Resources