简体   繁体   English

在 Java 中将 Char 数组转换为列表

[英]Converting Char Array to List in Java

Can anyone help me and tell how to convert a char array to a list and vice versa.谁能帮我告诉我如何将char数组转换为列表,反之亦然。 I am trying to write a program in which users enters a string (eg "Mike is good" ) and in the output, each whitespace is replaced by "%20" (Ie "Mike%20is%20good" ).我正在尝试编写一个程序,用户在其中输入一个字符串(例如"Mike is good" ),在 output 中,每个空格都被替换为"%20" (即"Mike%20is%20good" )。 Although this can be done in many ways but since insertion and deletion take O(1) time in linked list I thought of trying it with a linked list.虽然这可以通过多种方式完成,但是由于插入和删除在链表中需要 O(1) 时间,所以我想用链表来尝试它。 I am looking for someway of converting a char array to a list, updating the list and then converting it back.我正在寻找将char数组转换为列表、更新列表然后再将其转换回来的方法。

public class apples
{
   public static void main(String args[])
   {
      Scanner input = new Scanner(System.in);
      StringBuffer sb = new StringBuffer(input.nextLine());

      String  s = sb.toString();
      char[] c = s.toCharArray();
      //LinkedList<char> l = new LinkedList<char>(Arrays.asList(c));
      /* giving error "Syntax error on token " char",
         Dimensions expected after this token"*/
    }
}

So in this program the user is entering the string, which I am storing in a StringBuffer , which I am first converting to a string and then to a char array, but I am not able to get a list l from s .所以在这个程序中,用户正在输入字符串,我将其存储在StringBuffer中,我首先将其转换为字符串,然后转换为char数组,但我无法从s中获取列表l

I would be very grateful if someone can please tell the correct way to convert char array to a list and also vice versa.如果有人能告诉我将char数组转换为列表的正确方法,反之亦然,我将不胜感激。

In Java 8 and above, you can use the String 's method chars() :在 Java 8 及更高版本中,您可以使用String的方法chars()

myString.chars().mapToObj(c -> (char) c).collect(Collectors.toList());

And if you need to convert char[] to List<Character> , you might create a String from it first and then apply the above solution.如果您需要将char[]转换为List<Character> ,您可以先从它创建一个String ,然后应用上述解决方案。 Though it won't be very readable and pretty, it will be quite short.虽然它不会很可读和漂亮,但它会很短。

Because char is primitive type, standard Arrays.asList(char[]) won't work.因为 char 是原始类型,标准Arrays.asList(char[])将不起作用。 It will produce List<char[]> in place of List<Character> ... so what's left is to iterate over array, and fill new list with the data from that array:它将产生List<char[]>代替List<Character> ... 所以剩下的就是迭代数组,并用该数组中的数据填充新列表:

    public static void main(String[] args) {
    String s = "asdasdasda";
    char[] chars = s.toCharArray();

    //      List<Character> list = Arrays.asList(chars); // this does not compile,
    List<char[]> asList = Arrays.asList(chars); // because this DOES compile.

    List<Character> listC = new ArrayList<Character>();
    for (char c : chars) {
        listC.add(c);
    }
}

And this is how you convert List back to array:这就是您将 List 转换回数组的方式:

    Character[] array = listC.toArray(new Character[listC.size()]);




Funny thing is why List<char[]> asList = Arrays.asList(chars);有趣的是为什么List<char[]> asList = Arrays.asList(chars); does what it does: asList can take array or vararg .做它所做的: asList可以采用 array 或vararg In this case char [] chars is considered as single valued vararg of char[] !在这种情况下char [] chars认为单值可变参数char[] So you can also write something like所以你也可以写一些类似的东西

List<char[]> asList = Arrays.asList(chars, new char[1]); :) :)

Another way than using a loop would be to use Guava 's Chars.asList() method.除了使用循环之外的另一种方法是使用GuavaChars.asList()方法。 Then the code to convert a String to a LinkedList of Character is just:然后将字符串转换为字符的 LinkedList 的代码就是:

LinkedList<Character> characterList = new LinkedList<Character>(Chars.asList(string.toCharArray()));

or, in a more Guava way:或者,以更多番石榴的方式:

LinkedList<Character> characterList = Lists.newLinkedList(Chars.asList(string.toCharArray()));

The Guava library contains a lot of good stuff, so it's worth including it in your project. Guava 库包含很多好东西,因此值得将其包含在您的项目中。

Now I will post this answer as a another option for all those developers that are not allowed to use any lib but ONLY the Power of java 8:)现在,我将把这个答案作为另一个选项发布给所有那些不允许使用任何库而只能使用 java 8 的力量的开发人员:)

char[] myCharArray = { 'H', 'e', 'l', 'l', 'o', '-', 'X', 'o', 'c', 'e' };

Stream<Character> myStreamOfCharacters = IntStream
          .range(0, myCharArray.length)
          .mapToObj(i -> myCharArray[i]);

List<Character> myListOfCharacters = myStreamOfCharacters.collect(Collectors.toList());

myListOfCharacters.forEach(System.out::println);

You cannot use generics in java with primitive types, why?您不能在带有原始类型的 Java 中使用泛型, 为什么?

If you really want to convert to List and back to array then dantuch's approach is the correct one.如果您真的想转换为 List 并返回到数组,那么 dantuch 的方法是正确的方法。

But if you just want to do the replacement there are methods out there (namely java.lang.String 's replaceAll ) that can do it for you但是,如果您只想进行替换,则有一些方法(即java.lang.StringreplaceAll )可以为您完成

private static String replaceWhitespaces(String string, String replacement) {
    return string != null ? string.replaceAll("\\s", replacement) : null;
}

You can use it like this:你可以这样使用它:

StringBuffer s = new StringBuffer("Mike is good");
System.out.println(replaceWhitespaces(s.toString(), "%20"));

Output:输出:

Mike%20is%20good

All Operations can be done in java 8 or above:所有操作都可以在java 8或更高版本中完成:

To the Character array from a Given String从给定字符串到字符数组

char[] characterArray =      myString.toCharArray();

To get the Character List from given String从给定的字符串中获取字符列表

 ArrayList<Character> characterList 
= (ArrayList<Character>) myString.chars().mapToObj(c -> (char)c).collect(Collectors.toList());

To get the characters set from given String Note: sets only stores unique value.从给定的字符串中获取字符集注意:sets 只存储唯一值。 so if you want to get only unique characters from a string, this can be used.因此,如果您只想从字符串中获取唯一字符,则可以使用它。

 HashSet<Character> abc = 
(HashSet<Character>) given.chars().mapToObj(c -> (char)c).collect(Collectors.toSet()); 

To get Characters in a specific range from given String : To get the character whose unicode value is greater than 118. https://unicode-table.com/en/#basic-latin从给定的字符串中获取特定范围内的字符获取 unicode 值大于 118 的字符。https://unicode-table.com/en/#basic-latin

ASCII Code value for characters * az - 97 - 122 * AZ - 65 - 90字符的 ASCII 码值 * az - 97 - 122 * AZ - 65 - 90

 given.chars().filter(a -> a > 118).mapToObj(c -> (char)c).forEach(a -> System.out.println(a));

It will return the characters: w,x, v, z它将返回字符:w、x、v、z

you ascii values in the filter you can play with characters.您可以在过滤器中使用 ascii 值来处理字符。 you can do operations on character in filter and then you can collect them in list or set as per you need您可以对过滤器中的字符进行操作,然后您可以将它们收集在列表中或根据需要进行设置

I guess the simplest way to do this would be by simply iterating over the char array and adding each element to the ArrayList of Characters, in the following manner:我想最简单的方法是简单地遍历字符数组并将每个元素添加到字符数组列表中,如下所示:

public ArrayList<Character> wordToList () {
    char[] brokenStr = "testing".toCharArray();
    ArrayList<Character> result = new ArrayList<Character>();
    for (char ch : brokenStr) {
        result.add(ch);
    }
    return result;
}

List strList = Stream.of( s.toCharArray() ).map( String::valueOf ).collect( Collectors.toList() );

Try Java Streams.尝试 Java 流。

List<Character> list = s.chars().mapToObj( c -> (char)c).collect(Collectors.toList());

Generic arguments cannot be primitive type.通用 arguments 不能是原始类型。

if you really want to convert char[] to List, you can use.chars() to make your string turns into IntStream, but you need to convert your char[] into String first如果你真的想把char[]转换成List,你可以使用.chars()让你的字符串变成IntStream,但是你需要先把你的char[]转换成String

List<Character> charlist = String.copyValueOf(arrChr)
    .chars()
    .mapToObj(i -> (char) i)
    .collect(Collectors.toList());

Try this solution List<Character> characterList = String.valueOf(chars).chars().mapToObj(i -> (char) i).toList();试试这个解决方案List<Character> characterList = String.valueOf(chars).chars().mapToObj(i -> (char) i).toList();

列表构造函数是处理类型的另一种选择:

List filterList = Arrays.asList(jTextFieldFilterSet.getText().toCharArray());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM