scala list addall method - list

This is my java code,
public void test( List<Map> courses)
{
....
List<Map> data = (List<Map>) response.getBody();
courses.addAll(data);
pageNo = pagination(response.getHeaders());
if(pageNo!=null)
{
params.put("pageNo", pageNo);
pAccountCourses(params, courses);
}
}
How to convert it into scala List[AccountCourses] , so that i can add courseList into accountCourseslist
def test(courseList: java.util.ArrayList[AccountCourses]) {
......
//getting json data
var pageNo: String = null
val body = response.body
val json = parse(body)
var accountCourseslist = json.extract[java.util.ArrayList[AccountCourses]]
accountCourseslist.addAll(courseList)
if (pageNo != null) {
params.put("pageNo", pageNo);
test(accountCourseslist);
}
}
case class AccountCourses(id: Int) //case class
how to perform addAll operation of list in scala?

How to convert java.util.ArrayList[AccountCourses] to scala list?
use scala.collection.JavaConverters._ :
import scala.collection.JavaConverters._
val javaList = new java.util.ArrayList[Int]()
val scalaList = javaList.asScala
val scalaImmutableList = scalaList.toList // will return immutable copy
How to perform addAll operation of list in scala?
Use ++= if it is mutable collection or ++ on immutable list:
scalaList ++= List(1,2,3,4,5) // will also update javaList
val result = scalaImmutableList ++ List(1,2,3,4,5) // will return new copy

Related

Compare in Lists in Kotlin?

im trying to compare the value "hashtags" in Lists.
The class Person:
data class Person(var name: String, var age: Int){
val hashtags = mutableListOf<String>()
fun useHashtag(hashtag: String){
hashtags.add(hashtag) }
}
fun nextUser(){
for(item in alleBenutzerListe){
println(item)
print("\n")
}
}
The values:
val vlademir = Person("Vlademir",14)
val feton = Person("Feton",14)
val allUserList= listOf(Person(feton.name,14),listOf(Person(vlademir.name,14)))
Now in the main function I can use for to see all Persons in "allUserList"
if I add an hashtag for feton it works
feton.useHashtag("cooking")
feton.useHashtag("Football")
vlademir.useHashtag("Football")
vlademir.useHashtag("fortnite")
How could I compare the hashtags of these both?
val compareResult = vlademir.hashtags == feton.hashtags

Return list outside ForEach loop return only last item in Kotlin

I need to return all list items, in forEach it works fine, outside the loop it only returns the last item.
fun scanAndConvertFile(): String {
val scanner = Scanner(System.`in`)
print("Enter path to file to convert: ")
val fileName: String = scanner.nextLine()
val bufferedReader: BufferedReader = File(fileName).bufferedReader()
var result = bufferedReader.use { it.readText() }
val header = result.substring(0, result.indexOf(":61:"))
val body = result.substring(result.indexOf(":61:"), result.lastIndexOf(":61:220131C6"))
val footer = result.substring(result.lastIndexOf(":61:220131C6"), result.length)
var list = body.split(":61:")
list = list.filter { it.isNotEmpty() }
list = list.map {
":61:$it"
}
list.forEach() {
val part1 = it.substring(0, it.indexOf("?20"))
var part2ToBePasted = it.substring(it.indexOf("?20"), it.indexOf("?00"))
part2ToBePasted = part2ToBePasted.drop(3)
val part3 = it.substring(it.indexOf("?00"), it.indexOf("?27"))
var part4ToPast = it.substring(it.indexOf("?27"), it.indexOf("?28"))
part4ToPast = part4ToPast.drop(3)
val part5 = it.substring(it.indexOf("?28"), it.length)
list = if(part4ToPast.equals("")) {
listOf(part1.plus("?20").plus(part2ToBePasted).plus(part3).plus("?27").plus(part4ToPast).plus(part5))
} else {
listOf(part1.plus("?20").plus(part4ToPast).plus(part3).plus("?27").plus(part4ToPast).plus(part5))
}
// println(list) - works good
}
val converted = header.plus(list).plus(footer)
// println(converted) - print only last element of list
return converted
}
I tried to clean up your code a little (with no guarantee of course since I do not have any test data):
fun scanAndConvertFile(): String {
print("Enter path to file to convert: ")
val fileName: String = Scanner(System.`in`).nextLine()
val bufferedReader: BufferedReader = File(fileName).bufferedReader()
val result = bufferedReader.use { it.readText() }
val header = result.substring(0, result.indexOf(":61:"))
val footer = result.substring(result.lastIndexOf(":61:220131C6"), result.length)
val list = result
.substring(result.indexOf(":61:"), result.lastIndexOf(":61:220131C6"))
.split(":61:")
.filter { it.isNotEmpty() }
.map { ":61:$it" }
.map {
val indexOf00 = it.indexOf("?00")
val indexOf20 = it.indexOf("?20")
val indexOf27 = it.indexOf("?27")
val indexOf28 = it.indexOf("?28")
val substring27to28 = it.substring(indexOf27, indexOf28).drop(3)
it.substring(0, indexOf20)
.plus("?20")
.plus(if (substring27to28 == "") it.substring(indexOf20, indexOf00).drop(3) else substring27to28)
.plus(it.substring(indexOf00, indexOf27))
.plus("?27")
.plus(substring27to28)
.plus(it.substring(indexOf28, it.length))
}
return header.plus(list).plus(footer)
}
Basically you need to use map instead of forEach to return a list. map is used to transform each element of a list, while with forEach you do something to or with each element, but no list is returned.

return a new list from function in a for loop to pass in the updated list

I have a method that take a list as a parameter that performs some operation on it and returns the new list. However, in my for..loop I would to keep passing in the updated list until the for..loop has completed.
Is there a way to do this?
fun main(args: Array<String>) {
val listOfSeatRows = (1..127).toList()
// Just loop until all the listOfPass has completed.
listOfPass.forEach { seatPass ->
val seat = Seat.valueOf(seatPass.toString())
// I want to pass in the new updated list not the same list
getListOfSeatRows(listOfSeatRows, seat)
}
}
This method takes the list and return a updated list. However, in the for..loop above I would like to pass in the list that is returned from this method
private fun getListOfSeatRows(listOfSeat: List<Int>, seatPosition: Seat): List<Int> {
return when(seatPosition) {
Seat.F, Seat.L -> {
listOfSeat.windowed(listOfSeat.count() / 2).first()
}
Seat.B, Seat.R -> {
listOfSeat.windowed(listOfSeat.count() / 2).last()
}
}
}
enum class Seat(seat: Char) {
F('F'),
B('B'),
L('L'),
R('R')
}
Either you mutate the variable:
fun main(args: Array<String>) {
var listOfSeatRows = (1..127).toList()
// Just loop until all the listOfPass has completed.
listOfPass.forEach { seatPass ->
val seat = Seat.valueOf(seatPass.toString())
// I want to pass in the new updated list not the same list
listOfSeatRows = getListOfSeatRows(listOfSeatRows, seat)
}
}
or you mutate the list:
fun main(args: Array<String>) {
var listOfSeatRows = (1..127).toMutableList()
// Just loop until all the listOfPass has completed.
listOfPass.forEach { seatPass ->
val seat = Seat.valueOf(seatPass.toString())
// I want to pass in the new updated list not the same list
reduceListOfSeatRows(listOfSeatRows, seat)
}
}
private fun reduceListOfSeatRows(listOfSeat: MutableList<Int>, seatPosition: Seat) {
val half = listOfSeat.size / 2
when(seatPosition) {
Seat.F, Seat.L -> {
while (listOfSeat.size > half) listOfSeat.removeLast()
}
Seat.B, Seat.R -> {
while (listOfSeat.size > half) listOfSeat.removeFirst()
}
}
}
If you stick with mutating the property, your function can be simplified (and avoid wasteful creation of multiple intermediate lists) using take/takeLast:
private fun getListOfSeatRows(listOfSeat: List<Int>, seatPosition: Seat): List<Int> {
return when(seatPosition) {
Seat.F, Seat.L -> {
listOfSeat.take(listOfSeat.size / 2)
}
Seat.B, Seat.R -> {
listOfSeat.takeLast(listOfSeat.size / 2)
}
}
}
recursion
maybe that's will help with some enhancement depending on your code:
var ss = 1
val listOfPass = listOf<Char>('F', 'L','B','R')
fun main(args: Array<String>) {
val listOfSeatRows = (1..127).toList()
val answer = getListOfSeatRows(
listOfSeatRows,
listOfSeatRows.count() / 2,
Seat.valueOf(listOfPass[0].toString())
)
println(answer)
}
private fun getListOfSeatRows(listOfSeat: List<Int>, count: Int, seatPosition: Seat): List<Int> {
val tempList: List<Int> = when (seatPosition) {
Seat.F, Seat.L -> {
listOfSeat.windowed(count).first()
}
Seat.B, Seat.R -> {
listOfSeat.windowed(count).last()
}
else -> listOfSeat
}
if(count == 0 || count == 1) return listOfSeat
if (listOfPass.size > ss) {
val seat = Seat.valueOf(listOfPass[ss++].toString())
return getListOfSeatRows(tempList, count / 2, seat)
}
return listOfSeat
}

Kotlin - List within a List filtering

I have those data classes:
data class RouteType(
#SerializedName("type")
val type: String,
#SerializedName("items")
val items: List<RouteItem>)
data class RouteItem(
#SerializedName("id")
val id: String,
#SerializedName("route")
private val route: List<DoubleArray>)
I want to filter list of RouteType by type and filter list of RouteItem in it by id.
My code now:
// val filter: HashMap<String, List<String>>
val result = routeTypes // List<RouteType>
.filter { it.type in filter.keys }
.map {
routeType -> routeType.items.filter { it.id in filter[routeType.type]!! }
}
How to make .map return list with filtered list in it? Or maybe there's another way?
EDIT
Thanks, but flatmap not exactly what I need, I think. flatmap returns nested list(List<RouteItem>), but I want List<RouteType>.
I got it by this code:
val result = routeTypes
.filter { it.type in filter.keys }
.map {
routeType -> RouteType(
routeType.type,
routeType.items.filter { it.id in filter[routeType.type]!! })
}
Is there another way to get it?
Since your data is immutable (that's a good thing) you need to copy it while filtering. Use copy to make it more extensible:
val result = routeTypes
.filter { it.type in filter.keys }
.map { it.copy(items = it.items.filter { it.id in filter[routeType.type]!! }) }
You can use flatMap for this, it works as map, but merges all your mapped collections to one:
val result = routeTypes // List<RouteType>
.filter { it.type in filter.keys }
.flatMap {
routeType -> routeType.items.filter { it.id in filter[routeType.type]!! }
}

Get object of case class from regex match

i'm working on scraping data from a webpage with scala regex-es, but i encountered problem with parsing result to object of some case class-es.
In following snippet i managed to scrape all the data, but i have no clue how to parse 3 elements from an iterator. I thought about something like:
val a :: b :: c :: _ = result.group(0).iDontKnowWha
Any ideas what can i do?
import model.FuneralSchedule
import play.api.libs.json.Json
import scala.io.Source
var date = "2015-05-05"
val source = Source.fromURL("http://zck.krakow.pl/?pageId=16&date=" + date).mkString
val regex = "(?s)<table>.+?(Cmentarz.+?)<.+?</table>".r
var thing: List[FuneralSchedule] = List()
var jsonFeed: List[Funeral] = List()
val regMatcher = "("
case class Funeral(hour: String, who: String, age: String) {
override def toString: String = {
"Cos"
}
}
//implicit val format = Json.format[Funeral]
val out = regex.findAllIn(source).matchData foreach { table =>
thing ::= FuneralSchedule(table.group(1), clearStrings(table.group(0)))
"""<tr\s?>.+?</\s?tr>""".r.findAllIn(clearStrings(table.group(0))).matchData foreach { tr =>
//TODO: Naprawic bo szlak trafia wydajnosc
val temp = """<td\s?>.+?</\s?td>""".r.findAllIn(tr.group(0)).matchData.foreach {
elem => println(elem)
}
//println(Json.toJson(thingy))
}
println("Koniec tabeli")
}
thing
//Json.toJson(jsonFeed)
println(removeMarkers("<td > <td> Marian Debil </ td>"))
def removeMarkers(s: String) = {
s.replaceAll( """(</?\s?td\s?>)""", "")
}
def clearStrings(s: String) = {
val regex = "((class=\".+?\")|(id=\".+?\")|(style=\".+?\")|(\\n))"
s.replaceAll(regex, "")
}
One way of doing it would be converting it to a Stream and matching it using stream's operators like this:
val a #:: b #:: c #:: _ = """([a-z]){1}""".r.findAllIn("a b c").toStream
then a, b and c is what you're looking for