Searching an element in Java ArrayList
This tutorial example will show you how to search an element in Java ArrayList in both case sensitive and case insensitive way.Case sensitive search
package com.roytuts.java.arraylist;
import java.util.ArrayList;
import java.util.List;
public class SearchInArrayList {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
boolean found = list.contains("a");
System.out.println("element a : " + (found ?
"found" : "not found"));
found = list.contains("B");
System.out.println("element B : " + (found ? "found" : "not found"));
int index = list.indexOf("c");
System.out.println("element c : "
+ (index <= 0 ? "not found" : "found"));
index = list.indexOf("C");
System.out.println("element C : "
+ (index <= 0 ? "not found" : "found"));
}
} Output
element a : not found element B : found element c : not found element C : found
Case insensitive search
package com.roytuts.java.arraylist;
import java.util.ArrayList;
import java.util.List;
public class SearchInArrayListCaseInsensitive {
private boolean contains(String str, List<String> list) {
for (String s : list) {
if (str.equalsIgnoreCase(s))
return true;
}
return false;
}
private int indexOf(String str, List<String> list) {
if (str != null) {
for (int i = 0; i < list.size(); i++) {
if (str.equalsIgnoreCase(list.get(i))) {
return i;
}
}
}
return -1;
}
public static void main(String[] args) {
SearchInArrayListCaseInsensitive insensitive = new SearchInArrayListCaseInsensitive();
List<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
list.add("D");
list.add("E");
boolean found = insensitive.contains("a", list);
System.out.println("element a : " + (found ? "found" : "not found"));
found = insensitive.contains("B", list);
System.out.println("element B : " + (found ? "found" : "not found"));
int index = insensitive.indexOf("c", list);
System.out.println("element c : "
+ (index <= 0 ? "not found" : "found"));
index = insensitive.indexOf("C", list);
System.out.println("element C : "
+ (index <= 0 ? "not found" : "found"));
}
} Output
element a : found element B : found element c : found element C : found
Thanks for reading.
No comments