How can we intersect two lists in kotlin and save it in another variable(collection of String)
for example I have two lists like this
val list: MutableList<JSONArray> = Arrays.asList(requestedFields)
val otherList: MutableList<MutableList<String>> = Arrays.asList(requiredFields)
Any help is highly appreciated,
Thanks
You can use the intersect method: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/intersect.html
For example:
val first = listOf("Ragh", "Cat")
val second = listOf("Dog", "Ragh", "Giraffe")
val third = first.intersect(second)
println(third) // prints [Ragh]
Related
I have a below list
val list = listOf("o=one", "t=two", "t=two", "f=four", "o=one", "t=two", "s=seven", "o=one")
I wanna split it into list of the list contains [["o=one", "t=two", "t=two", "f=four"],["o=one", "t=two", "s=seven"],["o=one"]]
Actually I want to group list by "o=" delimiter and the list will always have at least one "0=" value. How could I achieve this in Kotlin without creating mutable var keyword because of my code should be in the functional style?
I have tried with group() and groupBy{} methods but couldn't get the expected result.
This might not cover all edge cases, and there might be better ways of doing it, but given that your requirements are not fully clear and extremely contrived, this should get you started either way. From here on out you can polish it yourself.
// Identifies indices of all "o=" elements in the list.
val splitAt = list
.withIndex()
.filter { it.value.startsWith( "o=" ) }
.map { it.index }
// Create sublists.
val split = splitAt
.windowed( 2, step = 1, partialWindows = true )
.map {
list.subList(
it[0],
if (it.count() == 1) it[0] + 1 else it[1]
)
}
I have 2 Lists as mentioned below:
val L1 = List[(Int,Int,String)]
val L2 = List[(Int,Int,String)]
I want to join these 2 lists on the basis of 1st and 2nd Int element in a way that result list must have 4 elements (Int,Int,String,String).
val joinedList = List[(Int, Int, String, String)]
where last 2 String elements will be string from L1 and string from L2.
Ex:-
val L1 = List((1,1,"one"), (2,2,"two"))
val L2 = List((2,2,"twice"), (3,3,"thrice"))
Output List ->
val joinedList = List((1,1,"one","--"),(2,2,"two","twice"), (3,3,"--","thrice"))
Kindly suggest a way to achieve that in scala.
First you want to get it into Maps, so it's easier to look up, then you can just map over all the keys:
val L1Map = L1.map{case (x,y,z) => ((x,y) -> z)}.toMap
val L2Map = L2.map{case (x,y,z) => ((x,y) -> z)}.toMap
val allKeys = L1Map.keySet ++ L2Map.keySet
val result = allKeys map {case (x,y) =>
(x, y, L1Map.getOrElse((x,y), "--"), L2Map.getOrElse((x,y), "--"))
}
That gives you an unsorted Set as a result. If you need a List, you can convert it back and sort it as necessary.
If I have a case class Point(x: Double, y: Double), and val s="(12,3.5),(33,42),(19.1,3)". How to split and convert s into something like this?
Vector(Point(12,3.5),Point(33,42),Point(19.1,3))
(I was thinking first need to split s into "(12,3.5)", "(33,42)" and "(19.1,3)" but I don't know how to do this in a clean way. Afterwards, some scala regular expressions can map each element into x and y for the Point class...)
I think below code might help you.
val s = "(12,3.5),(33,42),(19.1,3)"
val p = "[0-9.]+".r
val result = p.findAllIn(s).map(_.toDouble).grouped(2).map{case Seq(x, y) => Point(x, y)}.toVector
To extract tuples from the string, consider
val xs = """(\d+(\.\d*)?\,\d+(\.\d*)?)+""".r.findAllIn(s).toArray
Array(12,3.5, 33,42, 19.1,3)
To construct the points,
for (t <- xs; Array(x,y) = t.split(","))
yield Point(x.toDouble, y.toDouble)
which delivers
Array(Point(12.0,3.5), Point(33.0,42.0), Point(19.1,3.0))
I've a two lists dest (contains:x) and points (x,y)
dest:List[Int] and Points:List[(Int,Int)]
I want to filter elements in the dest, if it exists in points (x==points._1) i
var newl:List[Int] = List()
for(x<-dest) if(!points.filter(_._1==x).isEmpty) newl=newl:+x
I feel like there must be a better concise way with exists but tuple making it complex. So whats the best way to do the above?
Here is a concise way:
val dest= List(1,2,4,5)
val points = List((1,3), (2,3) , (3,4))
val newl = dest.filter{d => points.exists(_._1 == d)} // returns List(1, 2)
The following is even better order of complexity wise:
val dest= List(1,2,4,5)
val points = List((1,3), (2,3) , (3,4))
val xs = points.map{_._1}.toSet
val newl = dest.filter(xs.contains(_))
I am new to Scala and am a bit confused.
Given a list of lists List[List[Int]], how can one call a specific index of an element of each list, for example the second element of each list?
Simple:
val ints = List( List(1,2), List(3,4) )
val result = ints.map( l => l(1) )
This will produce (2,4).
While both of the other answers work, here is another version that is both safe to use and not complex. You can lift a Seq to a Function[Int, Option[A]] to make apply return Options instead of throwing exceptions. In Addition you can use flatMap instead of map{...}.flatten
List(List(1), List(1,2), List(1,2,3)).flatMap { xs =>
xs.lift(1)
}
// res1: List[Int] = List(2, 2)