Search code examples
javaarraylistjava-8scheduled-tasksjava-threads

How to printout a single line at time according to a schedule from an ArrayList?


I am trying to create a method that prints out a single line at a time, with two minutes delay between. How do I do that?.

This part of the code reads a text file (questionsFile) and creates an ArrayList:

public Broadcaster(Socket connection) throws IOException {

    read = new BufferedReader(new InputStreamReader(connection.getInputStream()));
    write = new PrintStream(connection.getOutputStream());  

    List<String> questionsList = new ArrayList<>();
    try (Stream<String> questionsStream = Files.lines(Paths.get(questionsFile))) {
        questionsList = questionsStream
                .parallel()
                .collect(Collectors.toList());

    } catch (IOException w) {
        w.printStackTrace();
    }

Here bellow there is a timer but for some reason, I can't make it work. The whole ArrayList is printed out with no delay what so ever. My intention is to use a printStream but for testing purposes, the text is currently printed out to the console. How can the code be rewritten so it prints out a single line at a time?

    List<String> finalQuestionsList = questionsList; 
    timer.schedule(task(() -> finalQuestionsList.forEach(System.out::println))
            , 120, TimeUnit.SECONDS.toMillis(1));
}

private TimerTask task(Runnable task) {
    return new TimerTask() {
        @Override
        public void run() {
            task.run();

Solution

  • The trivial solution would be:

    for (String question : questionsList) {
        timer.schedule(task(() -> System.out.println(question)), 0);
        try {
            sleep(2000);
        } catch (Exception ignored) {}
    }