List<String> to ArrayList<String> conversion issue

JavaListArraylist

Java Problem Overview


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 the following format

HashMap<String, ArrayList<String>>

so this method returns List and I need an ArrayList? If I try to cast it doesn't work out... 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?

Java Solutions


Solution 1 - Java

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);

Solution 2 - Java

First of all, why is the map a HashMap<String, ArrayList<String>> and not a HashMap<String, List<String>>? Is there some reason why the value must be a specific implementation of interface List (ArrayList in this case)?

Arrays.asList does not return a java.util.ArrayList, so you can't assign the return value of Arrays.asList to a variable of type ArrayList.

Instead of:

allWords = Arrays.asList(strTemp.toLowerCase().split("\\s+"));

Try this:

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

Solution 3 - Java

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);

Solution 4 - Java

In Kotlin List can be converted into ArrayList through passing it as a constructor parameter.

ArrayList(list)

Solution 5 - Java

Arrays.asList does not return instance of java.util.ArrayListbut 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+")));

Solution 6 - Java

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;

	}

Solution 7 - Java

This comes a bit late but thought of putting in a simple way for the answer of converting List to ArrayList.

Simple way

public static <T> ArrayList<T> listToArrayList(List<T> list) {
    return list != null ? new ArrayList<>(list) : null;
}

Classic way

public static  <T> ArrayList<T>  listToArrayList(List<T> list) {
    ArrayList<T> arrayList = new ArrayList<>();
    if (list != null) {
        for (int i = 0; i < list.size(); i++) {
            arrayList.add(list.get(i));
            i++;
        }
        // or simply
        // arrayList.addAll(list);
    }
    return  arrayList;
}

Usage

listToArrayList(yourList);

Solution 8 - Java

> ArrayList listOfStrings = new ArrayList<>(list.length); listOfStrings.addAll(Arrays.asList(list));

In case of object list you can use this way to convert Model[] list to ArrayList

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSkipper07View Question on Stackoverflow
Solution 1 - JavaSJuan76View Answer on Stackoverflow
Solution 2 - JavaJesperView Answer on Stackoverflow
Solution 3 - JavaMadProgrammerView Answer on Stackoverflow
Solution 4 - JavaShahab RaufView Answer on Stackoverflow
Solution 5 - JavaAmit DeshpandeView Answer on Stackoverflow
Solution 6 - JavaS KrishnaView Answer on Stackoverflow
Solution 7 - JavaGomez NLView Answer on Stackoverflow
Solution 8 - JavaZahid IqbalView Answer on Stackoverflow