javaswingstreamoption-typejprogressbar

Optional <Integer> cannot be converted to Int (for use on GUI Progress Bar)


I am receiving below error, when I try to set value on a JProgressBar.

"Optional cannot be converted to Int"

Could someone please advise any workarounds/Solution??

public GUI(){
    initComponents();
    tL = new TasksToDo();
    jProgressBar1.setValue(tL.retrieveTotalHours());// [Where my error occurs]}
}  

And from the TaskToDo Class, Originally I set this to ArrayList but the warnings said needed to switch to Optional:

  public class TasksToDo {

    public static ArrayList<Task> taskList;

    public TasksToDo(){
        taskList = new ArrayList<Task>();
        taskList.add(new Task(0,"Whitepaper", "Write first draft of Whitepaper",  7));
        taskList.add(new Task(1,"Create Database Structure", "Plan required fields and tables",  1));
        taskList.add(new Task(2,"Setup ODBC Connections", "Create the ODBC Connections between SVR1 to DEV-SVR",  2));

    }

    public void addTask (int taskId, String taskTitle, String taskDescription,  int taskHours){}

    public ArrayList<Task> retrieveTask(){
        return taskList;
    }

    public Optional<Integer> retrieveTotalHours(){
    return taskList.stream().map(e -> e.getTaskHours()).reduce(Integer::sum);
    }
}

Solution

  • You have to unwrap the optional and grab the value in it like this. Otherwise you can't assign an Optional where int is needed.

    tL.retrieveTotalHours().orElse(0);