Fania Indah
Fania Indah

Reputation: 135

How to compare string arraylist value and arraystring value in java

I have two arraylist like this :

ArrayList<String> hasil = new ArrayList<String>();
hasil.add("saya makan saya");
hasil.add("makan kamu dimana saya");
hasil.add("kamu dimana");

ArrayList<String> find = new ArrayList<>();
find.add("saya");
find.add("makan");

And I have code java like this :

String[] kata = new String[10];
for (int k = 0; k < find.size(); k++) {
    for (int i = 0; i < hasil.size(); i++) {
        kata = hasil.get(i).split(" ");
        for (int j = 0; j < kata.length; j++) {
            if (kata[j].equals(find.get(k))) {
                c++;
            }
        }
        System.out.println(find.get(k) + " = " + c);
        c = 0;
    }
}

I want to compare value in arraylist find with arraystring kata. The output that I have like this :

saya = 2 
saya = 1
saya = 0
makan = 1
makan = 1
makan = 0

Overall the output is correct. But I want get output of line. I want an output like this :

saya = 2; 
makan = 1;
saya = 1;
makan = 1;
saya = 0;
makan = 0;

Can anyone help me?

Upvotes: 0

Views: 137

Answers (2)

Porkko M
Porkko M

Reputation: 307

Here you go. :-)
Try this

String[] kata = new String[10];
for (int i = 0; i < hasil.size(); i++) {
    for (int k = 0; k < find.size(); k++) {

        kata = hasil.get(i).split(" ");
        for (int j = 0; j < kata.length; j++) {
            if (kata[j].equals(find.get(k))) {
                c++;
            }
        }
        System.out.println(find.get(k) + " = " + c);
        c = 0;
    }
}

Upvotes: 1

SANTOSHKUMAR SINGH
SANTOSHKUMAR SINGH

Reputation: 476

Just change the location of two lines as

for (int i = 0; i < hasil.size(); i++) {
        for (int k = 0; k < find.size(); k++) {

Complete code as follow

public static void main(String[] args) {
    System.out.println("Program Start");
    int c = 0;
    ArrayList<String> hasil = new ArrayList<String>();
    hasil.add("saya makan saya");
    hasil.add("makan kamu dimana saya");
    hasil.add("kamu dimana");

    ArrayList<String> find = new ArrayList<>();
    find.add("saya");
    find.add("makan");

    String[] kata = new String[10];
    for (int i = 0; i < hasil.size(); i++) {
        for (int k = 0; k < find.size(); k++) {

            kata = hasil.get(i).split(" ");
            for (int j = 0; j < kata.length; j++) {
                if (kata[j].equals(find.get(k))) {
                    c++;
                }
            }
            System.out.println(find.get(k) + " = " + c);
            c = 0;
        }
    }
}

Upvotes: 1

Related Questions