Leonel Leonel - 10 months ago 94
Java Question

Getting ArrayOutOfBound on Java 8

I am working on a Spring MVC project and I am getting an ArrayOutOfBound exception. If this was Java 7 then I would have no problem, but since it's Java 8 and I am new to it, I have no idea what the problem is. I have searched for about two days but have no luck. I would appreciate the help.

Now the out of bounds is caused by

class and specifically the
public Project find(Long projectId)...

Now my service class is:

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.stereotype.Service;
import com.spring.project.model.Project;

public class ProjectService {

private List<Project> projects = new LinkedList<>();

public ProjectService(){
Project javaProject = this.createProject("Java Project", "This is a Java Project");
Project javascriptProject = this.createProject("Javascript Project", "This is a Javascript Project");
Project htmlProject = this.createProject("HTML Project", "This is an HTML project");

this.projects.addAll(Arrays.asList(new Project[]{javaProject,javascriptProject, htmlProject}));

public List<Project> findAll(){
return this.projects;

public Project find(Long projectId){
return this.projects.stream().filter(p -> {
return p.getProjectId().equals(projectId);

private Project createProject(String title, String description){
Project project = new Project();

project.setAuthorizedFunds(new BigDecimal("100000"));
project.setAuthorizedHours(new BigDecimal("1000"));

return project;



Now my controller looks like this:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.spring.project.services.ProjectService;

public class ProjectController {

private ProjectService projectService;

public String findProject(Model model, @PathVariable("projectId") Long projectId){
model.addAttribute("project", this.projectService.find(projectId));
return "project";

public String find(Model model){
model.addAttribute("projects", this.projectService.findAll());
return "projects";

Answer Source

The problem is with the lambda expression in filter. Remove the return statement from the filter and try:

i.e. your code is very verbose and it should read as below:

return this.projects.stream().filter(p -> p.getProjectId().equals(projectId)).findFirst().get();

When you try to search an id that is not present you will get java.util.NoSuchElementException which is more meaningful. get(0) is the root cause of your java.lang.IndexOutOfBoundsException.