Java 8 streams, find object by predicate with null checks - java-8

I have a list of objects which I want to select one with a specific value but only if its null and I having a hard time doing this with java 8 streams.
String id = invoice.getDeliveries().stream().filter(delivery -> delivery.getName().equals("ABC")).findFirst().orElse(null).getId;
This code does not work when for example getName() returns null because then .getId will throw an exception.
How can I write this so that the value of id will just become null if ABC is null or does not exist?

Not a java expert, but maybe this works:
Delivery delivery = invoice.getDeliveries().stream().filter(delivery -> delivery.getName().equals("ABC")).findFirst().orElse(null);
String id = delivery == null ? null : delivery.getId;

Just change delivery.getName().equals("ABC") with "ABC".equals(delivery.getName()) and then check for null.
P.S. There is a good practice, to placce literals (like ABC) first. E.g. IntelliJ IDEA inspections check this.

Related

OptionSetValueCollection not taking a null value. Throws Generic SQL error when setting up the value to null

I'm creating a new record in CRM plugin(by reading the data from a related record) and the data that I'm passing may / may not contain "OptionSetValueCollection". Whenever the value for the OptionSetValueCollection is null the IOrganization.Create is throwing a Generic SQL exception.
Currently I'm checking the submitted value for null and when not null I'm not submitting a value for the created object.
My question is why does OptionSetValueCollection not taking null? Is this a platform issue?
I've also tried creating a List<OptionSetValue> object and adding the incoming OptionSetValues from the OptionSetValueCollection and then passing it to the target attribute, tried passing in null and also used the null-coalescing operator all with no luck.
//Earlybound code
Account account = new Account(){
Name = newBrand,
new_accounttype = new OptionSetValue((int)new_AccountType.Brand),
TerritoryId = siteRequestRecord.new_territoryid,
new_category1 = siteRequestRecord.new_category1 ?? null,
};
if (category2 != null)
{
account.new_category2 = siteRequestRecord.new_category2;
}
service.Create(account);
Seems to be a long outstanding issue.
There is a bug related to multiselect optionset - if you set it to null during creation that will trigger an error. But the same code that sets field to null works fine during update.
So if you set it to null during Create just don't set field value and as a result you'll get blank value of a field.
If I understand you want to set Optionset to null. use below code it shall work and set null for your optionset
new_accounttype = null;

Elasticsearch custom scoring function test null date values

I can't find anywhere examples of how to test null values in ES custom scoring functions.
According to the doc the scripts are in groovy, according to the log the script is evaluated in painless, but even with that I'm left puzzled by some errors
"script":"doc['response_rate'].value ? (doc['response_rate'].value + 1) : 0",
"lang":"painless",
"caused_by":{
"type":"wrong_method_type_exception",
"reason":"cannot convert MethodHandle(Doubles)double to (Object)boolean"}}}]
This seems to say I'm trying to cas a double to boolean and raises, but I need to test for non-null values.
How should I write my scoring script ?
EDIT : I have understood that in painless I cannot use the ternary ? : operator, so I must write explicitely doc['xx'].value != null. However, this seems to produce weird results for dates that were indexed with null values. It would seem that in painless the value is NOT null (although it is indeed null in the json when I GET /_search it) and the following does not work
"script":"(doc['unavailable_until'].value != null) ? 1 : 0"
and always seem to return 0 (as if the null date was actually not null). I have seen some people reporting something some weird default date, in this case how can I compare this date to something like Date.now ?
I wonder why I couldn't find this page before...
Basically, one can just call .empty to check for null values. Works with dates too
"script":"doc['unavailable_until'].empty ? 1 : 0",

Is there such thing as an empty date in C#

I am trying to input a date into an Oracle database. Sometime this value will be null. So in the function that I am writing I need a way to be able to pass in this null value. I am passing in this date as a parameter to stored proc. This parameter can be null. I am using the Oracle.DataAccess dll to get this thing to work. If it is indeed null, I am thinking of just throwing in a null variable. Do you think that would work??? Here is how I currently am setting up this scenario...
cmd.Parameters.Add("ACTIVE_DATEIn", DateTime.Parse(ActiveDate));
conn.Open();
outcome = cmd.ExecuteNonQuery();
Active Date is the possible null variable that I am going to pass in. Obviously you can't Convert a null value into a date Time. What would you guys suggest doing?
Since DateTime is a struct, it cannot contain a null value.
Some people use DateTime.MinValue to store a null value. A better approach would perhaps be to make ActiveDate a DateTime? instead.
Update:
You can also try something like:
cmd.Parameters.Add("ACTIVE_DATEIn", (ActiveDate == null ? OracleDate.Null : OracleDate.Parse(ActiveDate)));
You can make DateTime implement INullable by placing a ? after the type.
DateTime? date;
Which is ofcourse equivalent to
Nullable<DateTime> date;
You can use DateTime.MinValue instead of null, or make your DateTime object nullable.
You may need to use DBNull.Value in the case that your ActiveDate represents a null.

How do I return multiple xml elements/ attributes with linq, and create objects with them?

I'm working with an xml document in C# that has multiple (100+) points of stock market data. I'd like to create objects and add them to a List<> by passing initialization values retrieved from an xml document via linq. At the moment I'm just able to run a linq query and return one of the xml fields, in the code below, the attribute "symbol." I'd also like to return the document's "LastTradeDate, DaysLow, DaysHigh, LastTradePriceOnly, Open, and Volume." From there, my custom constructor is: StockDataPoint(Symbol, TradeDate, Open, High, Low, Close, Volume). A nudge in the right direction would be great. Here's the current linq:
var makeInfo =
from s in doc.Descendants("quote")
where s.Element("LastTradeDate") != null
&& s.Attribute("symbol") != null
let dateStr = s.Element("LastTradeDate").Value
where !string.IsNullOrEmpty(dateStr)
&& DateTime.Parse(dateStr, enUS) == targetDate
select s.Attribute("symbol").Value;
Well it depends on your XML format, but you might just want something like:
...
select new StockDataPoint((string) s.Attribute("symbol"),
(DateTime) s.Attribute("TradeDate"),
(decimal) s.Attribute("Open"),
(decimal) s.Attribute("High"),
(decimal) s.Attribute("Low"),
(decimal) s.Attribute("Close"),
(long) s.Attribute("Volume"));
Note that by use the explicit operators on XAttribute, you can avoid performing the parse yourself. Indeed, you can use this earlier in your query too:
var makeInfo = from s in doc.Descendants("quote")
where s.Attribute("symbol") &&
(DateTime?) s.Attribute("LastTradeDate") == targetDate
select ...
If the target of the cast is a nullable type (either a nullable value type or a reference type) then if the attribute is missing, the result will be the null value for that type, which is very handy.
You need to create a class:
select new YourClass {
Symbol = s.Attribute("symbol").Value,
...
}

Loading null values with CsvDataFileLoader in dbunit

We are using the CsvDataFileLoader to load in our reference data like so:
new InsertIdentityOperation(DatabaseOperation.CLEAN_INSERT)
.execute(connection,
new CsvDataFileLoader().load("/sql/ReferenceData/"));
Is there anyway to put null values into a csv that is loaded into our db.
I don't think there is, I would imagine that , null and NULL would all get interpreted as their string values.
Has anyone managed to do this or know of a work around for this problem?
CsvDataFileLoader uses CsvURLProducer to load and parse the data.
In that class on Line 145 for dbunit 2.4.8 you see the following:
if (CsvDataSetWriter.NULL.equals(row[col])) {
row[col] = null;
}
CsvDataSetWriter.NULL contains the string "null" therefore your assumption that null would get interpreted as a string value appears to be incorrect and you should use this in your CSV.
Of course this means that you can't have the string "null" in your fields but I'm sure this isn't often required.

Resources