-1

I have a question regarding linked-lists. How would you search through one which looks like this and find the string "Freda"?

private LinkedList<Boat> boats = new LinkedList<Boat>();

boats.add(new Boat(1, "Ed", 3));

boats.add(new Boat(2, "Fred", 7));

boats.add(new Boat(3, "Freda", 5));
3

6 Answers 6

0

I assume, getName is the getter that will return the name of the boat.

for(int i=0;i<boats.size();i++){
  if(searchedWord.equals(boats.get(i).getName()){
   //do your operation here
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

Itrate over your list and then search your value

for(Boat a: boats){
    if(a.name.equals("Freda")){ // name is the variable you have used to store "Fread" 
        //   sout("Found");
         break;
     }
}

1 Comment

Isn't Map a preferrable approach for this kind of searching !! PS: This clarifies what I am trying to say
0

Supposing that you have getters and setters on your Boat:

  public Boat search (LinkedList<Boat> list, String searchedName) {
      for (Boat boat : list) {
         if(boat.getName().equals(searchedName) {
               return boat;
                         }
                 }
     throw new IllegalArgumentExcetion("This boat was not found");
     }

Comments

0

As already Added In comments your should opt for Map<Key,Value> Pair Approach

private Map<String,Boat> boats = new HashMap<String,Boat>();
boats.put("ED",new Boat(1, "Ed", 3));
boats.put("Fred",new Boat(2, "Fred", 5));
boats.put("Ted",new Boat(3, "Ted", 8));

Then when you want to search you can always do this way :

boats.get("Fred");

Comments

0

If you want to search for stuff, you want to use an indexed collection like Data Store: https://github.com/jparams/data-store

Example:

Store<Boat> store = new MemoryStore<>() ;
store.add(new Boat(1, "Ed", 3));
store.add(new Boat(2, "Fred", 7));
store.add(new Boat(3, "Freda", 5));
store.index("name", Boat::getName);
Boat boat = store.getFirst("name", "Ed");

With data store you can create case-insensitive indexes and all sorts of cool stuff. If you are doing a lot of lookups, you definitely want to use a library like this over looping.

Comments

0

You can solve it easily via filtering the list stream;

final List<Boat> ed = boats.stream().filter(boat -> boat.name.equals("Ed")).collect(Collectors.toList());

This will return a list of all the boats with name Ed

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.