109

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?

0

9 Answers 9

211

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

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+")));
1
  • 3
    And specifically the UnsupportedOperationException is caused because the Arrays.asList method returns a fixed-sized list backed by an array - it cannot be modified. The solution presented here by @Jesper will avoid that. Oct 30, 2012 at 8:19
46

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

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

ArrayList(list)
5

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+")));
0

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;

    }
0

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

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

0

With the advent of the Java streaming API (March, 2014), the following might now be considered the preferred approach:

    public List<String> getWordsFunctionally(List<String> sentences) { 
        List<String> list = sentences.stream()
            .map(s -> List.of(s.toLowerCase().replaceAll("\\p{Punct}", "").split("\\s+")))
            .flatMap(List::stream)
//          .distinct() // if you don't want duplicates
            .collect(Collectors.toList());
        
        return list;
    }

Note that the original code had a bug in it: with each iteration, the values in allWords are replaced with the current array derived from splitting the sentence into words.

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

This should read

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

Also, it doesn't remove punctuation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.