I have a List of books and I want to do a case insensitive search of the book titles, to see if they contain a particular string. This string might be present as a word or a part of a word. My method keeps returning a null pointer exception...
``` private List<Book> books; private String search(String searchWord) { List<Book> searchResult = null; for(Book b : books) { boolean check = books.stream().filter(o -> b.getTitle().equals(searchWord)).findFirst().isPresent(); if (check = true) { searchResult.add(b); } else return searchWord + " not found"; } return buildResult(searchResult); } ``` Why is it that my searchResult list remains empty even after I am adding to it?
I do think that there is something wrong with my Boolean check...I think...but I can't seem to figure out what
It seems searchResult isn't initialized. Without creating the object by calling it's constructor, the list object wont really exist, nor will it have access to it's non-static methods or it's non-static field variables. Though List can't be initialized by doing new List<Book>(); because it's an interface: http://stackoverflow.com/questions/13395114/how-to-initialize-liststring-object-in-java Though you can initialize it to any of the classes that implement the List interface; my personal favorite is the ArrayList class. `List<Book> searchResult = new ArrayList<Book>();` I'm not sure what most of the method calls in your check do, though I'll add that I think the `String.contains()` method is a good way to test whether a String contains a certain CharSequence or not. ``` String s = "sSsffff 33"; System.out.println(s.contains("ss")); //false System.out.println(s.contains("ff 3")); //true ```
Thank you, well that...and a few other tweaks resulted in a method that now works :) The `else` part of the if-statement needed modification and the state of the Boolean 'check' needed to be returned to `false` for each iteration. ``` private String search(String searchWord) { List<Book> searchResult = new ArrayList<Book>(); int notFound = 0; for(Book b : books) { boolean check = false; check = b.getTitle().trim().toLowerCase().contains(searchWord.toLowerCase()); if (check != false) { searchResult.add(b); } else notFound++; } if (notFound == books.size()){ return "The word you are looking for, could not be found"; } return buildResult(searchResult); }
Looks clean, glad I could help :)
Join our real-time social learning platform and learn together with your friends!