In case you want to find an element in the Linked List in Java, there is an easy way to do so. That way of the implementation works if you have implemented the linked list with the constructor and the model class’s help. I have explained the details of implementing the linked list in this article.
Search implementation of the needed element in a linked list in Java.
Implementation of searching the Linked List element – is based on going through the list and displaying the message of success, in case the needed piece has been found. Otherwise, we avoid it. It works with the help of a counter. I am personally convinced that every developer should know, understand, and use the counter technique since this technique is straightforward to understand and reusable in many algorithms.
Code example of searching an element in the LinkedList in Java.
private void findTheElementInLinkedList() {
//You need to create linked list first
creatingLinkedList();
//Finding the first item from the list
ListNode current = head;
//Searched item
int searchedItemValue = 61;
//Position of the searched item
int positionOfSearchedItem = 0;
//Going through the list until last item don't have connection
while (current != null) {
//If item data is the same as searched value we have found it
if (current.data == searchedItemValue) {
Log.d("linkedList", "Item with value " + current.data + " has position number " + positionOfSearchedItem);
break;
}
//Increasing the counter if not find the item yet
positionOfSearchedItem++;
//Moves current item to the next
current = current.next;
}
}
In this article, you figured out how to find an element in the linked list java by value with the counter’s help. With the use of the Java collections and in case of implementation via constructor and model class.
Full code and more examples in my facebook group.
Useful links:
Leave Any Questions Related To This Article Below!