How can I convert ArrayList<Object> to ArrayList?

后端 未结 11 727
-上瘾入骨i
-上瘾入骨i 2020-11-28 06:31
ArrayList list = new ArrayList();
list.add(1);
list.add(\"Java\");
list.add(3.14);
System.out.println(list.toString());


相关标签:
11条回答
  • 2020-11-28 07:31

    Your code ArrayList<String> list2 = (String)list; does not compile because list2 is not of type String. But that is not the only problem.

    0 讨论(0)
  • 2020-11-28 07:36

    You can use wildcard to do this as following

    ArrayList<String> strList = (ArrayList<String>)(ArrayList<?>)(list);
    
    0 讨论(0)
  • 2020-11-28 07:36

    A simple solution:

    List<Object> lst  =listOfTypeObject;   
    ArrayList<String> aryLst = new ArrayList<String>();
        for (int i = 0; i < lst.size(); i++) {
            aryLst.add(lst.get(i).toString());
        }
    

    Note: this works when the list contains all the elements of datatype String.

    0 讨论(0)
  • 2020-11-28 07:37

    Using guava:

    List<String> stringList=Lists.transform(list,new Function<Object,String>(){
        @Override
        public String apply(Object arg0) {
            if(arg0!=null)
                return arg0.toString();
            else
                return "null";
        }
    });
    
    0 讨论(0)
  • 2020-11-28 07:38

    Using Java 8 you can do:

    List<Object> list = ...;
    List<String> strList = list.stream()
                               .map( Object::toString )
                               .collect( Collectors.toList() );
    
    0 讨论(0)
提交回复
热议问题