I’ve got String array with data.
And ArrayList for result:
String[] arr = word.split("aaccde");
List<Boolean> list = new ArrayList<>();
I need to compare each element with other elements.
If array contains element only one time – false
if array contains element several times – true
Output in List should be:
[true, true, true, true, false, false]
I try to use two loops, but it not worked corect:
for (int i = 0; i < arr.length; i++) {
for (int k = i + 1; k < arr.length; k++) {
if (!arr[i].equals(arr[k])) {
list.add(i, false);
} else {
list.add(i, true);
}
}
}
How to achieve result in list:
[true, true, true, true, false, false]
>Solution :
For each string in the array a, scan the array a for a matching string. The matching must not be itself !(i==j). The |= simply make b[i] true if there’s one or more matches.
import java.util.*;
public class Main{
public static void main(String[] args) {
String [] a = {"cat", "dog", "cat", "fish", "dog", "bear"};
boolean [] b = new boolean[a.length];
for(int i=0; i<a.length; i++)
for(int j=0; j<a.length; j++)
b[i] |= (i!=j && a[i].equals(a[j]));
System.out.println(Arrays.toString(b));
}
}
Output
[true, true, true, false, true, false]