3

I'm reading a file line by line and putting into a list. So, if my file has 10 lines, I have ten lists. Now, while doing this or after doing this, I want to add all the lists into an Array. So, I have an Array of Lists, without using "var", so essentially just 'val'. Here's what I have so far:

    val fileLines = Source.fromFile(filename).getLines.toList

    for (line <- fileLines) {
    if (!line.isEmpty) 
     println((line.toList).filter(e => e != ' '))
    }

I'm just converting every line into a list and removing blank elements. How do I generate a Array of Lists from this? Array being of type val and not try var.

2
  • 1
    it's funny! some posts say.. "it smells like homework, tag it as homework" and have that post upvoted 12times. and now, you say this! hmm.. anyways, point taken! Commented Nov 17, 2012 at 19:26
  • You might rephrase/edit the question. You say 10 lines would make ten lists. I think you mean a list with 10 items? Big difference. :/ Commented Mar 29, 2013 at 9:04

1 Answer 1

8

You could try something like this:

val myArray = fileLines.filterNot(_.isEmpty).map { line =>
    (line.toList).filter(e => e != ' ')
}.toArray

That will give you an array of list elements. You can remove the .toArray at the end if you want a List of Lists.

Sign up to request clarification or add additional context in comments.

6 Comments

I got this. but, why does printing arrays in scala, print the object? how do I go about..getting the, say.. (n,n)th element in the array of lists?
In the example above, if you use println(myArray), it will just call .toString on the object and display the output. To find something specific in a list, you could iterate over the elements with foreach and/or use something like the find(), collect() or filter() methods on List to get a specific elements. Combine with zipWithIndex and you will also have access to the index position. For an array, you would just reference the position, like: myArray(2) - just make sure make sure the position you specify is in bounds.
But, I can't run foreach on the above, as the elements of the lists (for example, myArray(i)) are of type 'Any'.
In the original example, it was - but in my example it should have a type: Array[List[Char]]. The reason it was [Any] originally was the else part of the if statement was not returning a typed value. In my example I removed the if, and replaced it with a filterNot to eliminate that.
Awesome I get it! Looks like it'll take quite sometime, for me to start thinking.."the functional" way. Any pointers on getting better at this?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.