Search code examples
javaarraylistjava-stream

Java: Cannot filter ArrayList using Java-Streams


The error I am getting

I am getting the error "The method map(Function<? super Car,? extends R>) in the type Stream<Car> is not applicable for the arguments

What I am trying to do

I am trying to filter the xx ArrayList but I keep getting this error and I don not or cannot tell why. I am new to Java so this is probably an error I have made

This is my code

import java.util.HashMap;
import java.util.ArrayList;
import java.util.stream.*; 
import java.util.Arrays;


public class BusCar
{
    // timetable
    String time;
    int platform;
    
    ArrayList<Car> xx = new ArrayList<Car>();

    String newline = System.getProperty("line.separator");
    public BusCar(String depTime, int plat)
    {
        // initialise instance variables
        depTime =  time;
        plat =  platform;
    }
    //filename A CSV file of Train records.

    public void addFromFile(String filename)
    {
        TrainReader reader = new TrainReader();
        xx.addAll(reader.getTrains(filename));
    }
    
    public void printBefore(String time)
    {
        // prints all trains which depart before the given time 
        // one train per line
       xx.stream().filter(i -> Integer.parseInt(i.departureTime) < Integer.parseInt(time)).map(i-> System.out.println(i),newline);
    }
}

Solution

  • It appears you want to do this. Your Car class needs to properly override toString()

    xx.stream().filter(i -> Integer.parseInt(i.departureTime) < 
       Integer.parseInt(time)).forEach(System.out::println);