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("."));
arrayList.add(a[0].split("\\.")[0]);
应如下
arrayList.add(a[0].split("\\.")[0]);
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));
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]);
}
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]
这对我来说是正常的: arrayList.add(a[0].split("\\\\.")[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());
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.