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);
}
}
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);
An Optional means that the value need not be there. It is basically there to force the caller to explicitly decide what to when a value does not exist. In your case, you can specifify a default value:
jProgressBar1.setValue(tL.retrieveTotalHours().orElse(0));
However, your retrieveTotalHours
method probably should not return an Optional in the first place. Stream.reduce
returns Optional.empty()
when the stream is empty, but in your case it probably should return 0
when the list of tasks is empty. So you can do:
public int retrieveTotalHours(){
return taskList.stream().map(e -> e.getTaskHours()).reduce(0, Integer::sum);
}
(The 0
argument is the identity, which is returned when the stream is empty.)
or even:
public int retrieveTotalHours(){
return taskList.stream().mapToInt(e -> e.getTaskHours()).sum();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With