To check if a string appears twice in an ArrayList
in Java, you can use a loop to iterate through the list and a counter variable to keep track of the number of times the string appears.
Here's an example of how to check if a string appears twice in an ArrayList
using a loop:
import java.util.ArrayList; public class Main { public static void main(String[] args) { ArrayList<String> list = new ArrayList<>(); list.add("apple"); list.add("banana"); list.add("apple"); String str = "apple"; int count = 0; for (String s : list) { if (s.equals(str)) { count++; } } if (count >= 2) { // string appears twice in the list } else { // string does not appear twice in the list } } }
In this example, the for
loop iterates through the elements of the ArrayList
and uses the equals
method to compare each element to the string "apple"
. If a match is found, the counter variable count
is incremented. After the loop finishes, the if
statement checks if the counter is greater than or equal to 2, indicating that the string appears twice in the list.
You can use a similar approach to check if a string appears more than twice in the list, by changing the condition in the if
statement to count >= 3
.