I'm running a filter command on an object in kotlin and trying to match results. I didn't realize until today that an empty string will match any string in a contains query as follows:
var brandname = ""
var brandtofind = "tide"
var result = brandtofind.contains(brandname) //results in true
This is problematic when you are trying to match entries where a string can be empty as follows:
var candidates = this.filter{ product ->
text.contains(product.name) ||
text.contains(product.brandname) //brandname often empty
I get massive numbers of false positives on products without a brand name. How do I alter the query to only match when there is a true match?
You can add a check for product.brandname.isNotBlank(), which is an enhanced verions of isNotEmpty()
var candidates = this.filter{ product ->
text.contains(product.name) ||
(product.brandname.isNotBlank() && text.contains(product.brandname))}
Related
Is there an easier approach to convert an Intellij IDEA environment variable into a list of Tuples?
My environment variable for Intellij is
GROCERY_LIST=[("egg", "dairy"),("chicken", "meat"),("apple", "fruit")]
The environment variable gets accessed into Kotlin file as String.
val g_list = System.getenv("GROCERY_LIST")
Ideally I'd like to iterate over g_list, first element being ("egg", "dairy") and so on.
And then ("egg", "dairy") is a tuple/pair
I have tried to split g_list by comma that's NOT inside quotes i.e
val splitted_list = g_list.split(",(?=(?:[^\\\"]*\\\"[^\\\"]*\\\")*[^\\\"]*\$)".toRegex()).toTypedArray()
this gives me first element as [("egg", second element as "dairy")] and so on.
Also created a data class and tried to map the string into data class using jacksonObjectMapper following this link:
val mapper = jacksonObjectMapper()
val g_list = System.getenv("GROCERY_LIST")
val myList: List<Shopping> = mapper.readValue(g_list)
data class Shopping(val a: String, val b: String)
You can create a regular expression to match all strings in your environmental variable.
Regex::findAll()
Then loop through the strings while creating a list of Shopping objects.
// Raw data set.
val groceryList: String = "[(\"egg\", \"dairy\"),(\"chicken\", \"meat\"),(\"apple\", \"fruit\")]"
// Build regular expression.
val regex = Regex("\"([\\s\\S]+?)\"")
val matchResult = regex.findAll(groceryList)
val iterator = matchResult.iterator()
// Create a List of `Shopping` objects.
var first: String = "";
var second: String = "";
val shoppingList = mutableListOf<Shopping>()
var i = 0;
while (iterator.hasNext()) {
val value = iterator.next().value;
if (i % 2 == 0) {
first = value;
} else {
second = value;
shoppingList.add(Shopping(first, second))
first = ""
second = ""
}
i++
}
// Print Shopping List.
for (s in shoppingList) {
println(s)
}
// Output.
/*
Shopping(a="egg", b="dairy")
Shopping(a="chicken", b="meat")
Shopping(a="apple", b="fruit")
*/
data class Shopping(val a: String, val b: String)
Never a good idea to use regex to match parenthesis.
I would suggest a step-by-step approach:
You could first match the name and the value by
(\w+)=(.*)
There you get the name in group 1 and the value in group 2 without caring about any subsequent = characters that might appear in the value.
If you then want to split the value, I would get rid of start and end parenthesis first by matching by
(?<=\[\().*(?=\)\])
(or simply cut off the first and last two characters of the string, if it is always given it starts with [( and ends in )])
Then get the single list entries from splitting by
\),\(
(take care that the split operation also takes a regex, so you have to escape it)
And for each list entry you could split that simply by
,\s*
or, if you want the quote character to be removed, use a match with
\"(.*)\",\s*\"(.*)\"
where group 1 contains the key (left of equals sign) and group 2 the value (right of equals sign)
I have a class called Person
data class Person(
val id: Int,
val name: String
)
data class IDs(
val id : Int,
val active : Boolean )
and an array list that has numbers of ids and another list of Persons
val myStu = listOf<Person>(Person(1, "Name_1"), Person(2, "Name_2"), Person(3, "Name_3"))
var ids = listOf<IDs>(IDs(1,false),IDs(2,true),IDs(3,true))
var newIds = listOf<Int>(2,3,4,6)
First I want to apply two actions to the myStu, first is to have a list that include all the items from myStu that his id matches the id in the IDS and only if the active is true
myStu or the new list will have the values
Person(2, "Name_2"), Person(3, "Name_3"))
Then do action two , I need to add a new item to the new list that their id does not exist in the newIds , in another word we will add a new person Person(4,"None") and (6,"None) , 4 and 6 values come from newIds list
the final output will be :
id= 2 name = "Name_2", id= 3 name = "Name_3", id= 4 name = "None" , id =6 name="None"
I want to write the code with filter , I failed with first step because I don't know how to use contains() with the list inside the filter
val newArr = myStu.filter {
ids.contains(it.id)
}
The "easiest" way of doing that would be to use filter directly, there's no need for contains. If we were to use contains, then we would need to also search for which element contained the id, in order to get the status. We can just do a .any() to do both at the same time.
V1
val activeStu = myStu.filter { person -> ids.any { it.id == person.id && it.active } }
val result = newIds.map { newId ->
activeStu.find { it.id == newId } ?: Person(id = newId, name = "None")
}
Another method, that might work a bit better if we have big lists, would be to first transform the IDs list into a map. That way the second part of our code is a bit more efficient, since there is no search involved.
V2
val idsMap = ids.associate { it.id to it.active }
val activeStu = myStu.filter { idsMap[it.id] ?: false }
//the creation of the result list is the same
Version without creating 2 new lists. This works, but it might be quite ineficient processing wise, and also harder to understand what is going on IMO.
V3
val result = newIds.map { newId ->
//try to find an IDs with the current newId and status as true
when (ids.find { it.id == newId }?.active) {
//if found, then find the corresponding Person
true -> myStu.find { it.id == newId } ?: Person(newId, "None") // if this happens, it means that an IDs with status true existed and no Person had that id. Not sure what you want in this scenario, this version creates one of the "none" persons.
//if not found, then create a new one
else -> Person(newId, "None")
}
}
Note: depending on what version of kotlin you have, you might have to change the when statement to this:
when (ids.find { it.id == newId }?.active == true)
Since I think I remember that null didn't used to be treated as false in old versions (I've run this with version 1.4.20).
Btw, you can also use this version with the idsMap from V2, just replace the when(...) with when(idsMap[newId] or when(idsMap[newId] == true) depending on the kotlin version.
I'm making my first app in Kotlin and there is a lot of syntax I don't know, and I was wondering if there is a better way to check if a list contains at least one non null entry.
For now my solution is:
var atLeastOneValue: Boolean
var i = 0
for (x in list) {
if (x != null) atLeastOneValue = true
else i++
}
if (list.size == i) atLeastOneValue = false
return atLeastOneValue
I'm working with MutableList<String>.
You can use contains function for that:
val hasNull = list.contains(null)
contains can also be called in the operator form, it corresponds to the operator in:
val hasNull = null in list
val hasNoNull = null !in list
In my Parse Class, I have a column of Names. I would like to query for all names that contain searchString = "om". The query should return all names that contain "om" such as `Tom, Dom, Rom, etc.)
I've tried:
searchString = "om" // something non-exact
var query = PFQuery(className: "NamesClass")
query.whereKey("Name", contains: searchString)
query.findObjectsInBackgroundWithBlock {
but Parse doesn't accept contains as a search parameter.
Seems like queries only accept exact strings
For substring matching, you should be using whereKey:containsString:
searchString = "om"
var query = PFQuery(className: "NamesClass")
query.whereKey("Name", containsString: searchString)
query.findObjectsInBackgroundWithBlock {
That should return any NamesClass object where Name has a substring equal to "om". So, Tom, Dominique, and Thomas will be returned. Frank won't.
I am re-writing a query which is created in response to user's entry into text fields in order to offer some protection against SQL injection attack.
SELECT DISTINCT (FileNameID) FROM SurNames WHERE Surname IN
('Jones','Smith','Armitage')
AND FileNameID IN ( SELECT DISTINCT (FileNameID) FROM FirstNames WHERE FirstName
IN ('John','William') )
There can be up to 3 other tables involved in this process.
The parameter lists can be up to 50-100 entries so building a parameterized query is tedious and cumbersome.
I am trying to create a Linq query which should take care of the parameterization and offer the protection I need.
This gives me what I need
var surnameValues = new[] { "Jones","Smith","Armitage" };
var firstnameValues = new[] { "John","William" };
var result = (from sn in db.Surnames
from fn in db.FirstNames
where surnameValues.Contains(sn.Surname) &&
firstnameValues.Contains(fn.FirstName)
select fn.FileNameID).Distinct().ToArray();
I now need a way to dynamically create this depending upon whether the user has selected/entered values in the surname or firstname text entry boxes?
Any pointers will be gratefully received
Thanks
Roger
you could combine all the logic into the query;
var surnameValues = new[] { "Jones","Smith","Armitage" };
var firstnameValues = null;
// Set these two variables to handle null values and use an empty array instead
var surnameCheck= surnameValues ?? new string[0];
var firstnameCheck= firstnameValus ?? new string[0];
var result = (from sn in db.Surnames
from fn in db.FirstNames
where
(!surnameCheck.Any() || surnameCheck.Contains(sn.Surname)) &&
(!firstnameCheck.Any() || firstnameCheck.Contains(fn.FirstName))
select fn.FileNameID).Distinct().ToArray();
Your query doesn't seem to have a join condition betwwen the Surnames table and the firstNames table?
You could dynamically build the query (as you appear to be doing I cross join I've used SelectMany)
var query=db.Surnames.SelectMany(sn=>db.FirstNames.Select (fn => new {fn=fn,sn=sn}));
if (surnameValues!=null && surnameValues.Any()) query=query.Where(x=>surnameValues.Contains(x.sn.Surname));
if (firstnameValues !=null && firstnameValues.Any()) query=query.Where(x=>firstnameValues.Contains(x.fn.FirstName));
var result=query.Select(x=>x.fn.FileNameID).Distinct();