I have ArrayList and i want to get him some specific object values and insert them to another ArrayList, but I can't get the specific values
val listA = ArrayList<User>()
this list contains some users with their id,name, and email so i need to get all user's whose names are john and id,email will be any value
You could use the filter function i.e
listA.filter { it.name == "john" }
or use groupBy with forEach i.e
listA.groupBy{ it.name }.forEach{name, list ->
//name: the key for each list according to their names
//list: a grouped list according to the names
}
Related
I have a list with words in it. I want to compare each letter in each word with the corresponding letter, and the largest one is printed first, and so on...
You can sort the list using Collections and get the required string. 0
index will have smallest and last index will have largest. If you want
vice versa you can use list in reverse order.
val modelList: ArrayList<String> = ArrayList()
modelList.add("Rock")
modelList.add("Undertaker")
modelList.add("Sting")
modelList.add("Austin")
modelList.add("John Cena")
Collections.sort(modelList,
Comparator<Any?> { str, str1 ->
str.toString().compareTo(str1.toString()) })
//After this call you modelList will be sorted as [Austin, John Cena, Rock, Sting, Undertaker]
I have a random number being generated,
this number is then assigned a random number
number = (1..NumberMax).random()
the number should cycle until the number is not saved within the RoomDb which i am checking with this function
#Query("SELECT EXISTS(SELECT * FROM Number_Table WHERE NumberID IN(:randomNumberID))")
fun hasItem(randomNumberID: Int):Boolean
I have a repeat function to set and add the number to the array
but also changing the number if it is contained in the roomDb or in array
repeat(5){
number = (1..ruleAmount.toInt()).random()
while(addUserNumber.CheckUserNumberRule(number) == true && numberarray.contains(number) {
number = (1..NumberMax).random()
}
numberarray.add(number)
}
my issue is that the numbers I get would be the same as the numbers as I have saved in RoomDb,
I am unsure if there's a better way to loop through to check if it is in the RoomDb and if it is in the array and if it is in either change the number until its not in either
Lets say that i have a list of AccountDto (getContats() -> List)that each has a column accountId
List<Int> list = accountsDao.getContactIds()
and i have a list of MessageDto, where messageDto has a field 'fromAccountId'.
I want to loop through the messageList and find what new fromAccountId i have that dont exist in my DB.
getAccounts().value?.let {
for ((every accountId from it.accountDto) in --(every fromAccountId in newMessages.list)--) {
if (it.contains(newFromAccountId))
println("fount $newFromAccountId")
}
}
Is there an elegant way to do that in Kotlin...?
You are using nested loops which is not a very good idea, since time complexity of this operation is O(n^2), performace will degrade very fast as the size of your lists increase.
Better approach on the expense of some extra memory would be to first create a set of all the accountId's from your Database, and then iterate over the messageList and for every accoutId check if the set contains this accountId.
// Store all the accountId's in a Set so that lookup is fast
var accountIds = getAccounts().map{it.accountId}.toSet()
// Iterate over the messageList and find the Id's that are not in Set
messageList.asSequence()
.filter { !accountIds.contains(it.fromAccountId) }
.forEach { println("fount $it") }
I have object called Reservation which contains column with name "object_entity" and inside is ParseObject from table Entity. I want to query only those Reservation which contains certain Entity.
val q = ParseQuery.getQuery<ParseObject>("Reservation")
if (!isOnline(c)){
q.ignoreACLs()
q.fromLocalDatastore()
}
q.whereEqualTo("object_entity", ticket.getParseObject("object_entity")?.objectId)
q.findInBackground { itemList, err ->
itemList //empty size 0
err //null
}
This is working as intended if you are online. But if you are offline it will return empty list. I've checked local datastore and all expected objects are there. But if I remove q.whereEqualTo it will return list of all Reservations without any problem (but I need specific ones).
ticket.getParseObject("object_entity")?.objectId is not null. It always contains objectId - checked in debugger
If I remove q.whereEqualTo I check all returned Reservation objects if they contains Entity.
This is inside findInBackground:
itemList.forEach { reservation ->
val entityObj = reservation.getParseObject("object_entity")
if (entityObj == null) createLog("FoundObj", "null") else
createLog("FoundObj", entityObj.objectId.toString())
}
Ive tried to add inside q.whereEqualTo specific Entity objectId. And it returned empty list. But if I removed q.whereEqualTo that specific object with specific objectId I wanted to get was returned in list.
I'm currently creating a simple contact app using Kotlin and MVVM Architecture, I was able to display contact's name and email address with recyclerview, but when a "Contact" doesn't have a name I want to display only the email address also sorting it alphabetically in the recyclerview either the data is a "name" or "email address".
my Goal (name, email)
- John, john#gmail.com
- kaila#gmail.com
- Lee, lee#gmail.com
I've tried altering my List variable with
for (contact in listContacts) {
if (contact.name == "" || contact.name.isEmpty()) {
contact.name = contact.email
}
}
but it will make contact.name to have the same value as contact.email and I don't want it. contact.name need to keep their original value which is "" or null for further feature.
I can't think of a way to resolve this issue by changing the query inside my DAO.
For that I think you have taken two variables in your pojo and model class.
Now, For displaying Name I think you have taken a simple TextView in your raw file or a xml file for the RecyclerView's raw (adapter).
All right.
Now, You are setting the name value from contact.name which is correct.
But, In case If there is no value in it, You are assigning the value of contact.email in to contact.name. That's the reason the value of name is changed.
To avoid this, why you can't set the value of contact.email directly to your TextView as below :
for (contact in listContacts) {
if (contact.name == "" || contact.name.isEmpty()) {
tv_user_name.setText(""+contact.email);
}else{
tv_user_name.setText(""+contact.name);
}
}
Here, tv_user_name is a TextView inside your raw file.
Simple..!
Alphabetic sorting use List.sortBy()
list.sortBy { if (!it.name.isNullOrEmpty()) it.name else it.email }
Whenever name is not present, it will check with email