I have a listOf Strings
val help = listOf("a","b","c")
And want to remove b from the list but not using index because I will get Strings randomly like this
val help = listOf("c","a","b")
How to do this?
You can filter the List using the condition item does not equal "b", likeā¦
fun main(args: Array<String>) {
// example list
val help = listOf("a","b","c")
// item to be dropped / removed
val r = "b"
// print state before
println(help)
// create a new list filtering the source
val helped = help.filter { it != r }.toList()
// print the result
println(helped)
}
Output:
[a, b, c]
[a, c]
Lists by default aren't mutable. You should use mutable lists instead if you want that. Then you can simply do
val help = mutableListOf("a","b","c")
help.remove("b")
or you can do it like this if help really needs to be a non-mutable list
val help = listOf("a","b","c")
val newHelp = help.toMutableList().remove("b")
using a filter like in deHaar's answer is also possible
Related
I have the following code snippet
val cachedNews = listOf(News(9, "https://009"), News(8, "https://234"), News(7, "https://345"))
val freshNews = listOf(News(1, "https://123"), News(2, "https://234"), News(3, "https://345"))
val result = freshNews.filter {fresh -> filter(cachedNews, fresh)}
private fun filter(cached: List<News>, fresh: News): Boolean {
cached.forEach { cachedItem ->
if (cachedItem.url == fresh.url) return true
}
return false }
When the code runs if cachedItem.url == fresh.url the list is filtered and the result is a list where the urls of the two lists are identical. However when i reverse equality like so cachedItem.url != fresh.url the list is not filtered at all. The sequence of execution changes.
When using the == sign, the first item of freshNews is compared with the first Item of cachedNews after that the secondItem of freshNews is compared with secondItem of cachedNews and so on.
When I use the != sign the all items of freshNews are compared against only the firstItem of cachedNews ??
Am I missing something or is my code just wrong?
I'm not sure what the specific problem is because your approach is quite confusing. Your custom filter function is actually more like a contains function.
What might be useful is to:
Extract the cached URLs to a set
Filter the new results by URLs that are not in the set.
fun main() {
val cachedNews = listOf(News(9, "https://009"), News(8, "https://234"), News(7, "https://345"))
val freshNews = listOf(News(1, "https://123"), News(2, "https://234"), News(3, "https://345"))
val cachedUrls = cachedNews.map { it.url }.toSet()
val result = freshNews.filterNot { cachedUrls.contains(it.url) }
println(result)
}
Result:
[News(id=1, url=https://123)]
Im trying to do following in simplest way.
I'd need to map list of objects into hashMap so that value1 is the key and value2 is entry object.
val map = mutableMapOf<String, Account>()
accountInfo.map {
map.put( it.value1 to it.value2 )
}
or
val map2 = accountInfo.map {
it.value1 to it.value2
}
but both are somehow wrong
first one says it only wants string as input.
Second one tells me its going to return List<Pair<String, Account>>
Why ?! thank you!
use put(x, y)
Not put( x to y)
I want to create zero padding ArrayList, like this.
val ls = arrayListOf<Int>(0,0,0,0,0)
Is there a way to create n-size zero padding array list than using loop?
// can create zero padding array list but not looks smart
val ls = arrayListOf<Int>()
for (i in 0..n){
ls.add(0)
}
You can create a MutableList (or a List) with size 5 filled with zeros:
val list = MutableList(5) { 0 }
and if you want it as an ArrayList:
val arrayList = ArrayList(list)
or:
val arrayList = ArrayList(MutableList(5) { 0 })
You can also do the following
var arrayList = IntArray(5).toCollection(ArrayList(5))
or following, because as of now MutableList returns an ArrayList
var mutableList = MutableList(5){0} as ArrayList<Int>
but this may break if MutableList changes to something other than ArrayList(may be LinkedList) in future and should be avoided.
Let's say I have some arrays:
val a = arrayOf("Pushups", "Benchpress", "Squats")
val b = arrayOf("Pushups", "Squats", "Benchpress")
val c = arrayOf("Pushups", "Squats", "Sit Ups")
I essentially want to create a function to see if the two arrays have the same information, even if they're in a different order:
checkSameInfo(a,b) //Should return true
checkSameInfo(a,c) //Should return false
Is there a way of doing this, other than using a ton of for loops?
StackOverflow has been immensely helpful in the last two months of learning kotlin, so thanks to anyone who replies :)
a.sorted() == b.sorted()
Hope this helps.
I would just convert them to sets and then check if the contents are equal. Like this:
fun <T> checkSameInfo(arr1: Array<T>, arr2: Array<T>) = arr1.toSet() == arr2.toSet()
If you worked with lists instead of a arrays, you could use containsAll:
fun <T> checkSameInfo(list1: List<T>, list2: List<T>) =
list1.containsAll(list2) && list2.containsAll(list1)
In Kotlin, how can I take the first n elements of this array:
val allColours = arrayOf(
Pair(Color.RED, Color.WHITE),
Pair(Color.RED, Color.BLACK),
Pair(Color.YELLOW, Color.BLACK),
Pair(Color.GREEN, Color.WHITE),
Pair(Color.BLUE, Color.WHITE),
Pair(Color.BLUE, Color.WHITE),
Pair(Color.CYAN, Color.BLACK),
Pair(Color.WHITE, Color.BLACK))
So how can I fill pegColours with the first say 3 Pairs?
var pegColours: Array<Pair<Color,Color>> = //???
I tried allColours.take but it gave an error:
Expecting an element
You need to specify the number of items you want to take.
allColours.take(3)
For a random number of random indices, you can use the following:
val indexes = arrayOf(2, 4, 6)
allColours.filterIndexed { index, s -> indexes.contains(index) }
Note that you can write an extension method for this:
fun <T> Array<T>.filterByIndices(vararg indices: Int) = filterIndexed { index, _ -> indices.contains(index) }
Alternatively, if the indices are consecutive, you can use slice:
allColours.slice(1..3)
The problem with your code that you create pairs with color constants which are Ints (allColours has type Array<Pair<Int, Int>>), but you expect Array<Pair<Color, Color>>. What you have to do is change type pegColours type and use take:
var pegColours: Array<Pair<Int, Int>> = allColours.take(3).toTypedArray()
Also you have to call toTypedArray() cause Array.take returns List rather than Array. Or you can change pegColours type as following:
var pegColours: List<Pair<Int, Int>> = allColours.take(3)
I know you already proposed the usage of take, but alternatively ranges and a simple map also help to write idiomatic code as shown next:
var pegColours = (0 until 3)
.map { allColours[it] }
.toTypedArray()
You are very close :)
val allColours = arrayOf("red", "blue", "green")
kotlin.io.println(allColours.take(2))
Will give you first two elements ["red", "blue"]
You have to specify the number of elements you want to take from the array