how to get substring items with in arraylist in java - java

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.

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

Related

How to access a single ArrayList in ArrayListMultiMap

I would like to get an entry from ArrayList in an ArrayListMultiMap. I am using Google Guava ArrayListMultimap and each key is associated with multiple array lists. For example, for the key1 I have 4 array lists, and each ArrayList contains 2 entries. I need to be able to access a particular ArrayList and get an entry from there so my question is how do I do it? Every time I try to access the value associated with the key it prints all 4 array lists but I need only one.
Multimap<String, ArrayList<String>> wordAsKey = ArrayListMultimap.create();
for (DictionaryEntries dict : DictionaryEntries.values()) {
ArrayList<String> list = new ArrayList<>();
String key = dict.getKey();
String partOfSpeech = dict.getPartOfSpeech();
String definition = dict.getDefinition();
list.add(partOfSpeech);
list.add(definition);
wordAsKey.put(key, list);
}
ArrayList<String> resultList = new ArrayList<>();
resultList.add(wordAsKey.get(word).toString());
System.out.println(resultList);
Prints
[[[noun, A set of pages.], [noun, A written work published in printed or electronic form.], [verb, To arrange for someone to have a seat on a plane.], [verb, To arrange something on a particular date.]]]
But I need it to print only [noun, A set of pages.]
you can try: get index value
int index = 0;
resultList.add(wordAsKey.get(word).get(index).toString());
Just do it like this -
ArrayList<String> list = (ArrayList<String>)wordAsKey.get(word);
String result = list.get(index);
System.out.println(result);
And you can check whether particular String is exist or not in List, then see below;
if(list.contains("search")){...}

Is there a way to filter out the elements of a List containing object having a String element based on another List of String

I have a List of an object List<Object> which Objects contains String elements . Now There is also another List of String List<String> .
I want the first List to only contain objects which are elements of the second list.
What is the most efficient way to do this?
You can use the contains() method of the list and that's convenient in your case since it will equals() check the Strings.
e.g.
List<String> otherList = new ArrayList<>();
List<Object> test = new ArrayList<>();
Iterator<Object> it = test.iterator();
while(it.hasNext()){
if(!otherList.contains(it.next().getString())) it.remove();
}
or in Java8 streams
test.stream().filter(e -> otherList.contains(e.getString()))
.collect(Collectors.toList());
This will generate you a new List.

Complex Hashmap ArrayList Generator

Here's some code:
ArrayList<String> List = new ArrayList<>();
Map<String, List<String> > map = new HashMap<String, List<String>>();
List.add("stringA");
List.add("stringB");
List.add("stringC");
for(int i = 0; i<List.size();i++){
String key = List.get(i);
List<String> value = new ArrayList<String>();
map.put(key, value);
}
This code takes whatever is in the ArrayList, loops through it, adds it to the Map, and then creates an empty ArrayList with each string name as the variable name. Now, this works, but there's one problem, unless I'm overlooking something. At some point, I will need to access the new empty ArrayLists that are in the map. However, I won't know what the titles of these ArrayLists are, without printing them out, which I don't want to do. Basically, I'm thinking I need a map method or class and then an additional map key method or class. I'm not sure how to implement it but maybe something like this:
public class MapKey {
public MapKey(int count, String header){
}
}
Map<MapKey, List<String> > map = new HashMap<MapKey, List<String>>();
Another option I've considered is to somehow loop through the map array and add Strings to each ArrayList, but I'm very new to maps and looping through them. Especially ones that contain ArrayLists as their values.
There're multiple ways to access keys and values of your HashMap:
for (Map.Entry<String,ArrayList<String>> entry : map.entrySet()) {
String key = entry.getKey();
ArrayList<String> value = entry.getValue();
// do your work
}
or
Set<String> keys = map.keySet();
for(String key : keys){
ArrayList<String> value = map.get(key);
}
Read the java HashMap api Java HashMap Link
Edit:
you dont need to loop through your outside ArrayList objects when you add all of its elements to another, just simply invoke addAll(), it will append all elements of an arraylist to another.
ArrayList<String> aList = map.get("stringA");
assume your first outside ArrayList is called outListOne;
aList.addAll(outListOne);
Appends to corresponding lists:
//assume number of outside lists are equal to number of map elements
String[] keysArr = {"stringA", "stringB", "stringC"};
ArrayList[] outLists = {outListOne, outListTwo, outListThree};
// adds outside lists to corresponding map ArrayList lists
for(int i = 0; i < keysArr.length; i++){
list = map.get(keysArr[i]); // you ArrayList in a map, get it by key name
list.addAll(outLists[i]); // append elements from out list to corresponding list
}
Not exactly sure what you mean by "titles of these ArrayLists." But here are a few code snippets that might give you a better idea of how to work with your map:
// add string x to the list for "stringA"
map.get("stringA").add(x);
// print all the values in the list for "stringC"
for (String s: map.get("stringC")) {
System.out.println(s);
}
// print the names of the lists that contain "xyzzy"
for (String key: map.keySet()) {
if (map.get(key).contains("xyzzy")) {
System.out.println(key);
}
}
// remove "foo" wherever it appears in any of the lists
for (List<String> list: map.values()) {
while (list.remove("foo")){}
}

Java: How to efficiently remove strings from array that do not exist in the second array?

I have two big arrays of strings. I want to remove the elements from the first array that do not exist in the second array.
First I create two arrays:
Array to modify:
String[] sarr = fdata.split(System.getProperty("line.separator"));
ArrayList<String> items = new ArrayList(Arrays.asList(sarr));
Filter array:
List<String> filter = new ArrayList<String>();
filter = Arrays.asList(voc.split(System.getProperty("line.separator")))
Then I create Iterator to iterate through the elements of the items array and check if the iterated item exists in filter array, if it does, remove it from items:
Iterator<String> it = items.iterator();
while (it.hasNext()) {
String s = it.next();
if (!filter.contains(s)) {
it.remove();
}
}
items arrays contains 286,568 strings and filter contains 100,000 strings. It appears that the operation takes too much time so I am not doing it efficiently.
Is there a faster way?
Just use different collection types. For the Filter, use HashSet for O(1) (instad of O(n) for ArrayList) search complexity, and for the items, use LinkedList instead of ArrayList - which will be more efficient for the remove operations.
I didn't test this code, but...
String[] sarr = fdata.split(System.getProperty("line.separator"));
LinkedList<String> items = new LinkedList(Arrays.asList(sarr));
Set<String> filter = new HashSet<String>();
filter = new HashSet(Arrays.asList(voc.split(System.getProperty("line.separator"))));
items.retainAll(filter);
When you call collection.contains(element) often for a large collection, you should not use an ArrayList, but rather a HashSet.
Set<String> filter = new HashSet<>();
Collections.addAll(filter, voc.split(System.getProperty("line.separator")));
A HashSet is an optimized data structure for looking up things.

Separating the elements of arraylist

I have an ArrayList that contains a messageId, then a -, then a username.
Example : E123-sam
I want to divide each element of my List such that the part before the - goes to one ArrayList and the part after that goes to an other ArrayList.
How can I do it?
Assuming you have these ArrayLists:
List<String> allStrings;
// ... initialization and filling of 'allStrings'
List<String> messageIDs = new ArrayList<>();
List<String> userNames = new ArrayList<>();
you can loop through elements of the ArrayList and use String#split(delimiter) to separate the string based in the delimiter:
for (String s : allStrings) {
String[] parts = s.split("-");
messageIDs.add(parts[0]);
userNames.add(parts[1]);
}
Note: This will work if all the strings in allStrings follows the pattern "something-something". If not, then you can check if the length of parts is correct before accessing its elements, otherwise you will get a IndexOutOfBoundsException.
If you plan to use Java 8, you could do:
List<String> listOfIds = original.stream().map(e -> e.split("-")[0]).collect(Collectors.toList());
List<String> listOfUsernames = original.stream().map(e -> e.split("-")[1]).collect(Collectors.toList());

Categories