简体   繁体   中英

How to convert a String of Integers to an ArrayList in Java?

I try to parse a textfile which has lines which look like the following:

@KEY,_,0,1,2,_,4,5,6, ...

The @KEY is just an identifier in the beginning while the following numbers are my data which I want to store in an ArrayList<Integer> .

I have a metadata class which contains the arraylist in which I want to insert there integers:

class MetaD {
    public List<Integer> key1, key2, key3 = new ArrayList<Integer>();
}

I parse the textfile line by line; when the line starts with @KEY , I want to add the elements to the key1 list. If there is an _ , it should be replaced with an empty value:

    if(line.startsWith("@KEY")){
        metaObject.key1 = Arrays.asList(line.replace("@KEY,", "").replace("_", "").trim().split("\\s*,\\s*"));
    }

I found out that this does not work with ArrayList<Integer> . key1 has to be of the type ArrayList<String> or ArrayList<Object> to make it work.

Is there a way to convert Integers in the same way? If not, my idea would be the following:

  • Convert everything to an ArrayList<String>
  • Iterate every item of this new ArrayList and convert it with Integer.parseInt() into an Integer.
  • Adding this new Integer to my ArrayList<Integer>

Would there be a more efficient or better way to archive my needs?


Edit: Since Tunaki wrote in the comments, that my idea will probably be the only possible way I tried to do the following:

    if(line.startsWith("@KEY")){
        List<String> channelTemp =  Arrays.asList(line.replace("@KEY,", "").replace("_", "1").split("\\s*,\\s*"));
        channelTemp.forEach(item -> metaObject.channel.add(Integer.parseInt(item)));
        System.out.println("done");
    }

Unfortunately, this throws a NullPointerException in the third line here and I don't have a clue why. I replaced _ with 1 for testing purposes to avoid a NumberFormatException . When I print out every object in the lambda function instead of adding them to my ArrayList<Integer> , I can see that all items have an Integer value. So why do I get an exception here?

Since you're almost there I'll give you a hand.

String line = "@KEY,_,0,1,2  , _,4,5,6,";
List<Integer> collect = Arrays.stream(line.replaceAll("@KEY|_", "").split(","))
        .map(String::trim)
        .filter(s -> !s.isEmpty())
        .map(Integer::valueOf).collect(Collectors.toList());
System.out.println(collect);

EDIT

To obtain the null you can alter the mapping process like:

List<Integer> collect = Arrays.stream(line.split(","))
        .skip(line.startsWith("@KEY") ? 1 : 0)
        .map(String::trim)
        .filter(s -> !s.isEmpty())
        .map(s -> "_".equals(s) ? null : Integer.valueOf(s)).collect(Collectors.toList());

You're trying to put in list of Integer a String:

metaObject.key1 = Arrays.asList(line.replace("@KEY,", "").replace("_", "").trim().split("\\s*,\\s*"));

Here line.replace(...) and trim() return a String , and split(...) returns a String[] . Therefore Arrays.asList(...) returns a List<String> here, that's not compatible with your definition of key1 ( List<Integer> ).

Yes, you can convert it to List<Integer> by call Integer.valueOf(...) or Integer.parseInt(...) .

But I would recommend to

  1. Use a new instance of List instead of Arrays.asList(...) because the latest one will produce an unmodifiable collection. Sometines it's not what you want :)
  2. Use something less specific than your own text format. What about JSON? There are a lot of libraries to simplify parsing/storing of the data.

Firstly, you should split your string with ",", then you try if your each String is an integer or not with an isIntegerMethod. If it is an integer, you can add it into the list.

public static void main(String[] args) throws IOException {
    String str = "@KEY,_,0,1,2,_,4,5,9";
    String [] strArr = str.split(",");
    List<Integer> intList = new ArrayList<Integer>();
    for (String string : strArr) {
        if (isInteger(string, 10)) {
            intList.add(Integer.valueOf(string));
        } else {
            System.out.println(string + " is not an integer");
        }
    }
    System.out.println(intList.toString());

}

public static boolean isInteger(String s, int radix) {
    if(s.isEmpty()) return false;
    for(int i = 0; i < s.length(); i++) {
        if(i == 0 && s.charAt(i) == '-') {
            if(s.length() == 1) return false;
            else continue;
        }
        if(Character.digit(s.charAt(i),radix) < 0) return false;
    }
    return true;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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