Kotlin compare two lists - if ids match overwrite it [closed] - kotlin

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I have two lists of Object. Both objects have an id val. I need to check both lists by the id val, if the id is the same take the object from list B and overwrite it in list A. Is there a simple up to date way to achieve this outcome in kotlin?
Ive been searching through the kotlin docs and other comparing list questions on here but I havent found anything in the docs or on here that matches my usecase

Not sure about how efficient this is but it works...
Sample Class
data class SomeClass(val id: Int, val someString: String) {
}
fun transformList(firstList: List<SomeClass>, secondList: List<SomeClass>): List<SomeClass> {
return firstList.map { firstClass ->
val tempItem = secondList.firstOrNull { it.id == firstClass.id }
tempItem ?: firstClass
}
}
basically, the function takes both the lists and compares each item with each other, and returns items from list 2 if the id is the same.
fun main() {
val listOne = listOf<SomeClass>(
SomeClass(0, "I am 0, from list 1"),
SomeClass(1, "I am 1, from list 1"),
)
val listTwo = listOf<SomeClass>(
SomeClass(0, "I am 0, from list 2"),
SomeClass(1, "I am 1, from list 2"),
)
println(transformList(listOne, listTwo))
}
Output
[SomeClass(id=0, someString=I am 0, from list 2), SomeClass(id=1, someString=I am 1, from list 2)]

Related

In the rust test, I don't care about the sequence of vec![]. What should i do? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last month.
Improve this question
enter image description here
Is there any disorderd arrays Or Do not judge the order when asserting?
What I do is sort both sides in the assert call itself. This only works if T implements Ord.
let result = my_function();
my_function.sort();
let target = vec![];
target.sort();
assert_eq!(result, target);
If your datatype does not support Ord, you can use sort_by with a FnMut that returns an instance of Ordering.
Note that this can have issues when there isn't one specific way a vector can be sorted.
Convert the Vec(s) to HashBag(s) that contains references to the items in the Vecs. That will disregard the order of items when asserting for equality:
[dependencies]
hashbag = "0.1.9"
#[test]
fn two_vecs_equal_independent_of_item_order() {
use hashbag::HashBag;
let actual = vec![1, 2, 3, 3];
let expected_fail = vec![3, 2, 1];
assert_ne!(
actual.iter().collect::<HashBag<&i32>>(),
expected_fail.iter().collect::<HashBag<&i32>>()
);
let expected_pass = vec![3, 2, 1, 3];
assert_eq!(
actual.iter().collect::<HashBag<&i32>>(),
expected_pass.iter().collect::<HashBag<&i32>>()
);
}

Kotlin - how to use sort function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
Hallo Ladys and Gentleman,
i strugle with a function.
I want convert a given String to a MutableMap.
String:
var testString = "hshhfzrt" + "hszrhhtnt"
function to use:
charMap.toList().sortedByDescending { (_, value) ->
value }.toMap()
Final Output should be a Sorted Char in a new String.
Output example(Not related to testString is just example):
hhh, lll, aaa,
I hope you can help me.
Thx for reading this and your time.
val testString = "hshhfzrt" + "hszrhhtnt"
val result = testString
.toList()
.sorted()
.groupBy { it }
.map { it.value.joinToString("") }
.joinToString(", ")
println(result) // Output: "f, hhhhhh, n, rr, ss, ttt, zz"

How do I pull entries from an ArrayList at random in Kotlin?

This is my first Kotlin project. I am learning as I go and I have reached a roadblock.
I have an ArrayList of questions that I want to pull into that app in a random order. I've tried assigning the .random to the point where the question is assigned (right now it is set to CurrentPosition-1) but that only randomized the question and didn't pull the correct answers along with the questions.
How do I either bundle the answers to the question or is there a better way to get the questions to shuffle in order? I plan on having 50+ questions but only 10 will show each time the test is taken. I don't want the same 10 questions showing each time the user opens the test.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_quiz_questions)
mQuestionsList=Constants.getQuestions()
setQuestion()
}
private fun setQuestion(){
val question = mQuestionsList!![mCurrentPosition-1]
defaultOptionsView()
if(mCurrentPosition == mQuestionsList!!.size){
submitBtn.text = "Finish"
}else{
submitBtn.text = "Submit"
}
progressBar.progress = mCurrentPosition
tv_progress.text = "$mCurrentPosition" + "/" + progressBar.max
tv_question.text = question!!.question
test_image.setImageResource(question.image)
tvOptionOne.text = question.optionOne
tvOptionTwo.text = question.optionTwo
tvOptionThree.text = question.optionThree
tvOptionFour.text = question.optionFour
}
private fun defaultOptionsView(){
val options = ArrayList<TextView>()
options.add(0, tvOptionOne)
options.add(1, tvOptionTwo)
options.add(2, tvOptionThree)
options.add(3, tvOptionFour)
Here is my Array
object Constants{
const val TOTAL_QUESTIONS: String = "total_questions"
const val CORRECT_ANSWERS: String = "correct_answers"
fun getQuestions(): ArrayList<Question>{
val questionsList = ArrayList<Question>()
val q1 = Question(
R.drawable.questionmark,
1,
"Who is Regional Manager of\n Dunder Mifflin Scranton?",
"Michael",
"Jim",
"Pam",
"Dwight",
1,
)
I appreciate any help at all. Thank you in advance.
list.shuffled().take(10) And make your mQuestionsList property type List instead of ArrayList since you don’t need to modify it after retrieval. You should also probably make it lateinit or initialize it at its declaration site so you won’t have to make the type nullable and have to resort to !!, which is generally a code smell. So I would declare it as var mQuestionsList: List<Question> = emptyList() and whenever you want new values do mQuestionsList = Constants.getQuestions().shuffled().take(10).

How to check array integer value in kotlin? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
i want to make check value function like below code.
enabled is true only if the integer array contains 5 or 16, otherwise enabled is false.
Anyone can help?
Use the default IntArray.any(predicate: (Int) -> Boolean) : Boolean function to check it. Example:
#Test
fun intArray_containsElement() {
val arrayTest = intArrayOf(1, 10, 50, 5, 6, 4, 3)
val isEnable = arrayTest.any { it == 5 || it == 16 }
assertEquals(true, isEnable) // Successfully
}
edit: As Duc Thang pointed out, using any is better because it only iterates the array once:
val IntArray.enabled: Boolean get() = any { it == 5 || it == 16 }
Previous less efficient version:
val IntArray.enabled: Boolean get() = contains(5) || contains(16)
Test:
fun main() {
println(intArrayOf(0).enabled)
println(intArrayOf(0, 5).enabled)
println(intArrayOf(1, 16).enabled)
println(intArrayOf(5, 16).enabled)
println(intArrayOf(19, 1000, 4).enabled)
}
Output:
false
true
true
true
false

How to filter a list by using the ids of another list?

I have a list of ids. I want to filter my list and only keep the values in that list that match the id.
fun filterHelper(ids: List<Int>, list: List<People>) {
list.filter { ids.contains(it.id) }
}
But this is very inefficient. It is essentially traversing the list O(n^2). Does Kotlin let me do better?
I asked a similar question about slicing maps recently. The answer is that there is no good built-in function, but you can work around by using a Set instead of a List for your ids, which gets you O(1) lookup time for the comparisons, so O(n) in total.
data class People(val id: Int)
fun main() {
val people = listOf(People(1), People(2), People(3), People(4))
val ids = setOf(2, 4)
val filtered = people.filter { it.id in ids }
println(filtered)
}
Output:
[People(id=2), People(id=4)]
It's worth mentioning that if you already have a list, you can easily convert to a set with:
list.toSet()