Java - run a Scanner on a List<String>?

snotnose

Ars Praefectus
3,454
Subscriptor
I've massaged my file input and now have a List<String> where each line has 4 fields separated by whitespace. I want to run a Scanner on it to parse each line. Can I do that?

More generally, I have a List<String> that has whitespace separated fields. I'd love to create a class defining each field, then have 1 glorious doohicky to parse a line into that object.

Each line has the format "int int char string"

Example: Line is "2 12 c doremi"

I'd love to make a:
class stuff {
int a;
int b;
char c;
String line;
};

And magically slurp a line into a stuff. But I'm perfectly happy ignoring stuff and slurping each field of a line into it's variables.

I've actually just spent 3 hours relearning Java streams to get my massaged input List and am in a streams mindset.

I'm also scared at how much Java I've forgotten in the last 2-3 years.
 

snotnose

Ars Praefectus
3,454
Subscriptor
I can't get this to compile for the life of me.
Code:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

public class Foo
{
    class Stuff {
        int     min;
        int     max;
        char    letter;
        String  password;
    }

    List<String> readFile(String fileName) throws IOException
    {
        // Read the input file into List input.  Along the way we strip lines
        // with less than 5 chars (e.g. blank lines), replace '-' with ' ',
        // delete ':'.
        List<String> data =
            Files.lines(Paths.get(fileName))
                 .filter(word -> word.length() > 5)
                 .map(line -> line.replaceAll("-", " "))
                 .map(line -> line.replaceAll(":", ""))
                 .collect(Collectors.toList());
        
        return data;
    }
    List<Stuff> makeStuff(List<String> inputData)
    {
        List<Stuff> listOfStuff = inputData
            .stream()
            .map(input -> {
                String[] tokens = input.split(" ");
                return new Stuff(Integer.parseInt(tokens[0]),
                                 Integer.parseInt(tokens[1]),
                                 tokens[2].charAt(0),
                                 tokens[3]);
            })
            .collect(Collectors.toList());
    }

    void run(String fileName)
    {
        try
        {
            List<String> input = readFile(fileName);
            System.out.println(input);
        } catch(IOException e){
            System.out.println(e.toString());
        }

        List<Stuff> listOfStuff = makeStuff(data);
        System.out.println(listOfStuff);
    }

    public static void main(String[] args) throws IOException
    {
        Foo foo = new Foo();
        foo.run("Foo.txt");
    }
}

 javac Foo.java
Foo.java:40: error: constructor Stuff in class Foo.Stuff cannot be applied to gi
ven types;
                return new Stuff(Integer.parseInt(tokens[0]),
                       ^
  required: no arguments
  found: int,int,char,String
  reason: actual and formal argument lists differ in length
Foo.java:45: error: incompatible types: inference variable T has incompatible bo
unds
            .collect(Collectors.toList());
                    ^
    equality constraints: Foo.Stuff
    lower bounds: Object
  where T is a type-variable:
    T extends Object declared in method <T>toList()
Foo.java:58: error: cannot find symbol
        List<Stuff> listOfStuff = makeStuff(data);
                                            ^
  symbol:   variable data
  location: class Foo
3 errors

I can fix the third error easily enough, but the first 2 are causing me fits. help?
 

Apteris

Ars Tribunus Angusticlavius
9,590
Subscriptor
Code:
Foo.java:40: error: constructor Stuff in class Foo.Stuff cannot be applied to gi
ven types;
                return new Stuff(Integer.parseInt(tokens[0]),
                       ^
  required: no arguments
  found: int,int,char,String
You need to declare a constructor using those four parameters, in the Stuff class. At the moment it's attempting to use the default (no-args) constructor.
 

Lt_Storm

Ars Tribunus Angusticlavius
21,345
Subscriptor++
Code:
List<Stuff> listOfStuff = inputs
    .stream()
    .map(input -> {
        String[] tokens = input.split(" ");
        return new Stuff(Integer.parseInt(tokens[0]), Integer.parseInt(tokens[1]), tokens[2].charAt(0), tokens[3]);
    })
    .collect(Collectors.toList());

Now, that doesn't work at all.... After all, given the input

Code:
12 13 c Hello world

It throws "world" away. So you need to be quite a bit more clever in dealing with the strings. A regex is probably a better tool for the parsing than is split...
 

Lt_Storm

Ars Tribunus Angusticlavius
21,345
Subscriptor++
Now, that doesn't work at all.... After all, given the input

Code:
12 13 c Hello world


It throws "world" away.

My input spec is "4 fields separated by whitespace. Int Int Char String". "Hello World" violates that.

Strings can contain spaces (and newlines). So, if one of the fields is a string, then "foo bar" matches it. You need to beware of that because some idiot will probably do it.
 

Apteris

Ars Tribunus Angusticlavius
9,590
Subscriptor
I see my original post wasn't clear on that, my bad.
I thought it was clear. :D

Strings can contain spaces (and newlines). So, if one of the fields is a string, then "foo bar" matches it. You need to beware of that because some idiot will probably do it.
This, however, is true. Reminds me of this one time when we found backslashes and newlines in user logins, in the database...
 

snotnose

Ars Praefectus
3,454
Subscriptor
Sneaky Pete has already checked if the input has exactly 4 fields and thrown an error otherwise.

To get back to my original question, if I have a List<String> and want to feed that list to a scanner, how would I do that?

Keep in mind the Java streams questions have been answered, as have the regex questions. I'm just curious how I can feed a List/Array/ArrayList/whatever to a scanner.