-7

I have arraylist of strings, I need to find the substrings among the items in same arraylist?

For example:

ArrayList<String> ar = new ArrayList();
ar.add("UserId");  //adding item to arraylist
ar.add("Directory");
ar.add("Username");
ar.add("PhoneNumber");

Here I want to find substring of items, basically I need output as UserId and Username from the list items. how can I do it can someone help me out.

dokgu
  • 4,957
  • 3
  • 39
  • 77
sharan
  • 63
  • 1
  • 10
  • I am not sure what you are trying to accomplish here, but you can use a foreach on the arraylist or even filters, so you only have what you need – Edu G Jan 10 '17 at 17:07
  • @Rampraksh: My arraylist will have dynamic values so from those values list i need to find substring among them that it. – sharan Jan 11 '17 at 03:26

1 Answers1

2

you have two approaches:

    ArrayList<String> ar = new ArrayList();
    ar.add("UserId");  //adding item to arraylist
    ar.add("Directory");
    ar.add("Username");
    ar.add("PhoneNumber");

    // approach one using iteration 
    for (Iterator<String> it = ar.iterator(); it.hasNext(); ) {
        String f = it.next();
        if (f.equals("UserId"))
            System.out.println("UserId found");
    }

    // approach two using a colletion which supports fetching element by key 
    Map<String,String> myMap=new HashMap<>();
    for(String strg:ar){
        myMap.put(str,str);
    }

    String result=myMap.get("UserId");

If you have repeating element (for example several "UserId" element), you can use collections that support bags (sets with duplicate elemets), for example guava mutiset

Mr.Q
  • 4,316
  • 3
  • 43
  • 40
  • In your second aproach you put `str,str` in the map which are undefined variables. Also, whats the point of the map? why put the same object as key and value and then use it to retreive itself? Im confused... – fill͡pant͡ Jan 10 '17 at 17:59
  • @fillpant we need a collection which can provide us with the functionality to retrieve elements by name, java set dose not provide such functionality so we have to use some thing else such as map – Mr.Q Jan 10 '17 at 18:42
  • Hmm well ArrayList has the method `indexOf(Object value)` and `contains(Object value)` which might do the trick, but still i dont get the point of puting the value in with the same key and then retreiving it? I mean, if i have a String such as `"Hello"` whats the point of puting in in the map like: `map.put("Hello","Hello")` and then retreiving it using `map.get("Hello")` which returns `"Hello"`? :S Mainly asking due to curiocity xD – fill͡pant͡ Jan 10 '17 at 21:09