convert string to arraylist in java

前端 未结 7 885
别跟我提以往
别跟我提以往 2020-12-10 01:03

How to convert a String without separator to an ArrayList.

My String is like this:

String str = \"abcd...\"


        
相关标签:
7条回答
  • 2020-12-10 01:32
    String myString = "xxx";
    ArrayList<Character> myArrayList = myString.chars().mapToObj(x -> (char) x).collect(toCollection(ArrayList::new));
    myArrayList.forEach(System.out::println);
    
    0 讨论(0)
  • 2020-12-10 01:33
    public static void main(String[] args) {
            // TODO Auto-generated method stub
            String str = "abcd...";
            ArrayList<Character> a=new ArrayList<Character>();
            for(int i=0;i<str.length();i++)
            {
                a.add(str.charAt(i));
    
            }
            System.out.println(a);
        }
    
    0 讨论(0)
  • 2020-12-10 01:37

    Sorry for the Retrobump, but this is now really easy!

    You can do this easily in Java 8 using Streams! Try this:

    String string = "testingString";
    List<Character> list = string.chars().mapToObj((i) -> Character.valueOf((char)i)).collect(Collectors.toList());
    System.out.println(list);
    

    You need to use mapToObj because chars() returns an IntStream.

    0 讨论(0)
  • 2020-12-10 01:38

    use lambda expression to do this.

    String big_data = "big-data";
    ArrayList<Character> chars
            = new ArrayList<>(
                     big_data.chars()
                    .mapToObj(e -> (char) e)
                    .collect(
                            Collectors.toList()
                    )
            );    
    
    0 讨论(0)
  • 2020-12-10 01:48

    you can do it like this:

    import java.util.ArrayList;
    
    public class YourClass{
    
        public static void main(String [] args){
    
            ArrayList<Character> char = new ArrayList<Character>();
            String str = "abcd...";
    
            for (int x = 0; x < str.length(); x ++){
                char.add(str.charAt(x));
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-10 01:49

    You need to add it like this.

    String str = "abcd...";
    ArrayList<Character> chars = new ArrayList<Character>();
    for (char c : str.toCharArray()) {
      chars.add(c);
    }
    
    0 讨论(0)
提交回复
热议问题