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?
Convert list To ArrayList In Java. ArrayList implements the List interface. If you want to convert a List to its implementation like ArrayList, then you can do so using the addAll method of the List interface.
We can easily convert String to ArrayList in Java using the split() method and regular expression.
To convert string to ArrayList, we are using asList() , split() and add() methods. The asList() method belongs to the Arrays class and returns a list from an array. The split() method belongs to the String class and returns an array based on the specified split delimiter.
1) First split the string using String split() method and assign the substrings into an array of strings. We can split the string based on any character, expression etc. 2) Create an ArrayList and copy the element of string array to newly created ArrayList using Arrays. asList() method.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With