I have a following method...which actually takes the list of sentences and splits each sentence into words. Here is it:
public List<String> getWords(List<String> strSentences){
allWords = new ArrayList<String>();
Iterator<String> itrTemp = strSentences.iterator();
while(itrTemp.hasNext()){
String strTemp = itrTemp.next();
allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));
}
return allWords;
}
I have to pass this list into a hashmap in a following format
HashMap<String, ArrayList<String>>
so this method returns List and I need a arrayList? If I try to cast it doesn't workout... any suggestions?
Also, if I change the ArrayList to List in a HashMap, I get
java.lang.UnsupportedOperationException
because of this line in my code
sentenceList.add(((Element)sentenceNodeList.item(sentenceIndex)).getTextContent());
Any better suggestions?
Arrays.asList
does not return instance of java.util.ArrayList
but it returns instance of java.util.Arrays.ArrayList
.
You will need to convert to ArrayList if you want to access ArrayList
specific information
allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));
Take a look at ArrayList#addAll(Collection)
Appends all of the elements in the specified collection to the end of this list, in the order that they are returned by the specified collection's Iterator. The behaviour of this operation is undefined if the specified collection is modified while the operation is in progress. (This implies that the behaviour of this call is undefined if the specified collection is this list, and this list is nonempty.)
So basically you could use
ArrayList<String> listOfStrings = new ArrayList<>(list.size());
listOfStrings.addAll(list);
Cast works where the actual instance of the list is an ArrayList
. If it is, say, a Vector
(which is another extension of List
) it will throw a ClassCastException.
The error when changing the definition of your HashMap is due to the elements later being processed, and that process expects a method that is defined only in ArrayList
. The exception tells you that it did not found the method it was looking for.
Create a new ArrayList
with the contents of the old one.
new ArrayList<String>(myList);
In Kotlin List can be converted into ArrayList through passing it as a constructor parameter.
ArrayList(list)
Tried and tested approach.
public static ArrayList<String> listToArrayList(List<Object> myList) {
ArrayList<String> arl = new ArrayList<String>();
for (Object object : myList) {
arl.add((String) object);
}
return arl;
}
Source: Stackoverflow.com