[Solved] how to get substring items with in arraylist in java

Introduction

If you are looking for a way to get substring items within an ArrayList in Java, then you have come to the right place. In this article, we will discuss how to get substring items within an ArrayList in Java. We will look at different methods of doing this, such as using the subList() method, using the stream() method, and using the for loop. We will also discuss the advantages and disadvantages of each method. By the end of this article, you should have a better understanding of how to get substring items within an ArrayList in Java.

Solution

You can use the subList() method of the ArrayList class to get a sublist of items from an ArrayList.

Example:

ArrayList list = new ArrayList();
list.add(“Apple”);
list.add(“Banana”);
list.add(“Orange”);
list.add(“Mango”);

// Get sublist from index 1 to index 3
List subList = list.subList(1, 3);

// Print the sublist
System.out.println(subList);

// Output: [Banana, Orange]


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

3

solved how to get substring items with in arraylist in java