🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.
▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube
▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube
indexOf method, and the Stream API (Java 8 and later).Table of Contents
- Introduction
- Using Loops
- Using
indexOfMethod - Using
StreamAPI - Conclusion
Introduction
In Java, lists are dynamic data structures that store elements of the same type. Finding the index of a specific element can be done using various methods, each suited to different scenarios.
Using Loops
One way to find the index of an element is by iterating through the list using a loop.
Example
import java.util.ArrayList;
import java.util.List;
public class FindIndexExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("date");
String element = "cherry";
int index = findIndex(list, element);
if (index != -1) {
System.out.println("Element \"" + element + "\" found at index: " + index);
} else {
System.out.println("Element \"" + element + "\" not found in the list.");
}
}
public static int findIndex(List<String> list, String element) {
for (int i = 0; i < list.size(); i++) {
if (list.get(i).equals(element)) {
return i;
}
}
return -1; // Element not found
}
}
Explanation
- A loop is used to iterate through the list.
- The element is compared with each list element.
- If the element is found, its index is returned.
- If the element is not found,
-1is returned.
Output:
Element "cherry" found at index: 2
Using indexOf Method
The indexOf method provided by the List interface is a convenient way to find the index of an element.
Example
import java.util.ArrayList;
import java.util.List;
public class FindIndexExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("date");
String element = "cherry";
int index = list.indexOf(element);
if (index != -1) {
System.out.println("Element \"" + element + "\" found at index: " + index);
} else {
System.out.println("Element \"" + element + "\" not found in the list.");
}
}
}
Explanation
- The
indexOfmethod is called on the list with the element as the argument. - If the element is found,
indexOfreturns the index of the first occurrence of the element. - If the element is not found,
indexOfreturns-1.
Output:
Element "cherry" found at index: 2
Using Stream API
The Stream API (introduced in Java 8) provides a modern and concise way to find the index of an element in a list.
Example
import java.util.ArrayList;
import java.util.List;
import java.util.OptionalInt;
import java.util.stream.IntStream;
public class FindIndexExample {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("apple");
list.add("banana");
list.add("cherry");
list.add("date");
String element = "cherry";
int index = findIndex(list, element);
if (index != -1) {
System.out.println("Element \"" + element + "\" found at index: " + index);
} else {
System.out.println("Element \"" + element + "\" not found in the list.");
}
}
public static int findIndex(List<String> list, String element) {
OptionalInt indexOpt = IntStream.range(0, list.size())
.filter(i -> list.get(i).equals(element))
.findFirst();
return indexOpt.orElse(-1); // Element not found
}
}
Explanation
- An
IntStreamis created with a range of indices from0to the size of the list. - The
filtermethod is used to keep only the indices where the element is found. - The
findFirstmethod returns the first matching index as anOptionalInt. - If the element is found, the index is returned.
- If the element is not found,
-1is returned.
Output:
Element "cherry" found at index: 2
Conclusion
Finding the index of an element in a list in Java can be accomplished using various methods, each with its own advantages. Using loops provides a clear and straightforward approach, suitable for any type of list. The indexOf method offers a concise and direct way to achieve the same result with less code. The Stream API provides a modern and functional programming approach, making the code more readable and expressive. Depending on your specific use case and preferences, you can choose the method that best fits your needs.
My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:
Build REST APIs with Spring Boot 4, Spring Security 7, and JWT
[NEW] Learn Apache Maven with IntelliJ IDEA and Java 25
ChatGPT + Generative AI + Prompt Engineering for Beginners
Spring 7 and Spring Boot 4 for Beginners (Includes 8 Projects)
Available in Udemy for Business
Building Real-Time REST APIs with Spring Boot - Blog App
Available in Udemy for Business
Building Microservices with Spring Boot and Spring Cloud
Available in Udemy for Business
Java Full-Stack Developer Course with Spring Boot and React JS
Available in Udemy for Business
Build 5 Spring Boot Projects with Java: Line-by-Line Coding
Testing Spring Boot Application with JUnit and Mockito
Available in Udemy for Business
Spring Boot Thymeleaf Real-Time Web Application - Blog App
Available in Udemy for Business
Master Spring Data JPA with Hibernate
Available in Udemy for Business
Spring Boot + Apache Kafka Course - The Practical Guide
Available in Udemy for Business
Comments
Post a Comment
Leave Comment