2

I want to append a and b string arrays to arrayList. But "1.0" have to be "1" using with split. Split method returns String[] so arrayList add method does not work like this. Can you suggest any other way to doing this ?

String[] a = {"1.0", "2", "3"};
String[] b = {"2.3", "1.0","1"};

ArrayList<String> arrayList = new ArrayList<String>();

arrayList.add(a[0].split("."));
6
  • 1
    what is the expected output, not clear Commented Dec 17, 2014 at 10:25
  • a[0].split(".")[0] Commented Dec 17, 2014 at 10:25
  • just get the first element of the split array Commented Dec 17, 2014 at 10:26
  • The argument of split() is a regular expression, so if you want your delimiter to be ., you have to escape it such that it becomes \\.. Commented Dec 17, 2014 at 10:31
  • @Deniz because . is splitted using \\. in java, refer to answers Commented Dec 17, 2014 at 10:33

7 Answers 7

6
arrayList.add(a[0].split("\\.")[0]);
Sign up to request clarification or add additional context in comments.

3 Comments

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
Corrected it, faulty regex.
Firstly thanks, i had exception like this: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
2

Should be as below

arrayList.add(a[0].split("\\.")[0]);

Comments

2

Split method returns an array. You have to access to his position to get the number.

arrayList.add(a[0].split("\\.")[0]);

You can also use substring method:

arrayList.add(a[0].substring(0, 1));

Comments

1

Access first element of that array like this :

for (int i = 0; i < a.length; i++) {
    if (a[i].contains("."))
        arrayList.add(a[i].split("\\.")[0]);
    else
        arrayList.add(a[i]);
}

1 Comment

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 0
0

Why split it?. Just use a replaceAll(), it will be more efficient as it won't create an array of Strings.

public static void main(String[] args) {
    String[] a = { "1.7", "2", "3" };
    List<String> arrayList = new ArrayList<String>();
    for (int i = 0; i < a.length; i++) {

        arrayList.add(a[i].replaceFirst("\\..*", "")); // escape the . (match it as a literal), then followed by anything any number of times.
    }
    System.out.println(arrayList);

}

O/P :
[1, 2, 3]

Comments

0

If you use Java 8,

String[] a = {"1.0", "2", "3"};

List<String> list = Arrays.stream(a).map(s -> s.split("\\.")[0]).collect(Collectors.toList());

// OR

List<String> list2 = Arrays.stream(a).map(s -> {
  int dotIndex = s.indexOf(".");
  return dotIndex < 0 ? s : s.substring(0, dotIndex);
}).collect(Collectors.toList());

Comments

0

This is working properly for me: arrayList.add(a[0].split("\\.")[0]);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.