-3

I have an array list abc which has certain values -

ArrayList< String > abc = new ArrayList<>();
abc.add("hi");
abc.add("hello Yash");
abc.add("i am Yash");
String x = "Yash";

Now, I want to know if x is contained in any of the elements of abc.
If it is, then get the index of the elements which contain x.

Yash
  • 11
  • 1
  • 6

3 Answers3

1

Here is a simple solution:

public class FindText
{


    public static void main(String[] args)
    {
        ArrayList< String > abc = new ArrayList<>();
        abc.add("hi");
        abc.add("hello Yash");
        abc.add("i am Yash");
        String x = "Yash";

        for(int i=0; i<abc.size(); i++)
        {
            if(abc.get(i).contains(x))
            {
                int index = i;
                System.out.println(index);
            }
        }
    }
}

It gives you 1 and 2 as indexes which includes the text "Yash"

Elham Kohestani
  • 3,013
  • 3
  • 20
  • 29
0

You can achieve this in 2 different ways...

  1. The old school
  2. and the lambdas way

Old school Example:

public static void main(String[] args) {
    List<String> abc = new ArrayList<>();
    abc.add("hi");
    abc.add("hello Yash");
    abc.add("i am Yash");
    String x = "Yash";
    List<String> resultOldSchool = new ArrayList<>();
    for (String sentence : abc) {
        if (sentence.contains(x)) {
            resultOldSchool.add(sentence);
        }
    }
    System.out.println(resultOldSchool);
}

Lambdas way Example:

public static void main(String[] args) {
    List<String> abc = new ArrayList<>();
    abc.add("hi");
    abc.add("hello Yash");
    abc.add("i am Yash");
    String x = "Yash";
    List<String> resultJava8 = findStringInList(abc, x);
    if (!resultJava8.isEmpty()) {
        System.out.println(resultJava8);
    }
}

public static List<String> findStringInList(final List<String> list, final String strng) {
    return list.stream().filter(s -> s.contains(strng)).collect(Collectors.toList());
}

feel free to decide....

Community
  • 1
  • 1
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97
0

Assuming that abc is a List<String> and x is a String then this should do the trick.

List<Integer> indexes = new LinkedList<Integer>();
for(int i = 0; i < abc.size(); i++)
{
    if(abc.get(i).contains(x))
         indexes.add(i);
}

After the loop finishes all the indexes of the elements that contain x will be in the indexes list.

Alex A
  • 368
  • 2
  • 7