Grouping the nested loop elements based on the first iteration variable in Java

Sojimanatsu :

I have 2 lists one for the sentence one for the keywords. The idea is to check if the sentence have the keywords. and put them in a list for each sentence in order.

I am sorry if this is already duplicated here in advance.

List <String> sentence= new ArrayList <>();
sentence.add("this is a good dog");
sentence.add("cats drink milk");
sentence.add("Animals are beautiful creatures");

List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");

My idea was to create 2 nested loops for each list:

for (int b = 0; b < sentence.size(); b++) {
    for (int c = 0; c < keyword.size(); c++) {
        if (sentence.get(b).contains(keyword.get(c))) {
            System.out.println(keyword.get(c));
        }
    }
}

The output of this is:

dog
good
this
cats
milk
beautiful
are

The desired output would be:

[this,good,dog]
[cats,milk]
[are,beautiful]

So it is like getting all the existing keywords, in the order of the sentence,not related to keywords order.

and then group the existing keywords for each sentence, as in the order of existence.

Hope it is clear. Would really appreciate any ideas. doesnt have to follow the same method.

Eritrean :

Iterate over your sentence list. For each sentence iterate over your keyword list. Add each found keyword found in a tempList, sort the tempList by the index of keyword in sentence and finally add each tempList to a list of lists. Example:

public static void main(String[] args) {
    List <String> sentence= new ArrayList <>();
    sentence.add("this is a good dog");
    sentence.add("cats drink milk");
    sentence.add("Animals are beautiful creatures");

    List <String> keyword= new ArrayList <>();
    keyword.add("dog");
    keyword.add("cats");
    keyword.add("beautiful");
    keyword.add("good");
    keyword.add("are");
    keyword.add("this");
    keyword.add("milk");

    List<List<String>> result = new LinkedList<>();
    for(String sen: sentence){
        List<String> tempList = new ArrayList<>();
        for(String key: keyword){            
            if(sen.contains(key)){
                tempList.add(key);
            }
        }
        tempList.sort(new Comparator<String>() {
                @Override
                public int compare(String o1, String o2) {
                   return sen.indexOf(o1) -  sen.indexOf(o2) ;
                }
        });
        result.add(tempList);
    }
    for(List<String> r : result){
        System.out.println(r);
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=127942&siteId=1