Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Compare elements in String java

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading