coconut
coconut

Reputation: 1101

Applying method to stream

I'm learning how to use streams in Java. I have a file with some info that I want to load in some data structure, for example, a Set.

I wrote a function to parse each line.

private Food parseFoodLine(String line){
    String[] items = line.split("|");
    Food food = #Parsing done here. 
    return food;
}

But how do I put each line through that method?

private Set<Food> loadFood(){
    Set<Food> food = new HashSet<>();
    try (Stream<String> stream = Files.lines(Paths.get("myFile"))) {
        stream.forEach(parseFoodLine());
    } catch (IOException e) {
        System.err.println("Error parsing file");
    }
}

I understand I should do "stream.forEach(food::add)" but how do I get a food object from my file?

Upvotes: 3

Views: 111

Answers (1)

Eran
Eran

Reputation: 393771

You can map the elements of your Stream<String> to Food instances (via your parseFoodLine method) and them use collect to collect them into a Set:

food = stream.map(Food::parseFoodLine).collect(Collectors.toSet());

Note that your Food class should override equals and hashCode properly in order for Food instances to be correctly stored in a HashSet.

Upvotes: 6

Related Questions