KaiquanMah's picture
"" + someInt; Integer.parseInt(str)
38e72ed verified
raw
history blame
3.06 kB
Write the method
ArrayList<Integer> numList(ArrayList<String> list)
which takes a list of strings as its parameter.
Strings containing numbers.
The method returns a new list of integer type, with the contents of the strings converted to integers.
Example method call:
public static void main(String[] parameters){
ArrayList<String> list = new ArrayList<>();
list.add("2");
list.add("10");
list.add("-999");
System.out.println(numList(list));
}
Program outputs:
[2, 10, -999]
==========================================
import java.util.Random;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
public class Test{
public static void main(String[] args){
final Random r = new Random();
testaa(new int[]{4,20,3,6,7,8,9,11});
testaa(new int[]{1,5,2,4,3,6,4,7,5,8,6,3,9,5,3});
testaa(new int[]{-5,-4,-1,-2,-3,-6,-7});
int pituus = r.nextInt(10) + 10;
int[] l = new int[pituus];
for (int i=0; i<pituus; i++) {
l[i] = (100 - r.nextInt(200));
}
testaa(l);
}
// testaa used by main
public static void testaa(int[] l) {
ArrayList<String> lista = new ArrayList<>();
// convert from int to string element
for (int a : l) {
lista.add("" + a);
}
System.out.println("Testing with list ");
System.out.print("");
tulosta(lista);
// convert BACK from string to integer element
System.out.println("As integers: " + numList(lista));
System.out.println("");
}
// tulosta used by testaa
public static void tulosta(ArrayList<String> lista) {
System.out.print("[\"");
// so the joined string becomes
// [" from above
// 1", "2", "3
// ", " is the 'delimiter'
// "] from below
System.out.print(String.join("\", \"", lista));
System.out.println("\"]");
}
// numList used by testaa
public static ArrayList<Integer> numList(ArrayList<String> list) {
ArrayList<Integer> list2 = new ArrayList<>();
// convert string to integer element
// https://www.geeksforgeeks.org/java/integer-valueof-vs-integer-parseint-with-examples/
for (String s : list) {
list2.add(Integer.parseInt(s));
}
return list2;
}
}
Testing with list
["4", "20", "3", "6", "7", "8", "9", "11"]
As integers: [4, 20, 3, 6, 7, 8, 9, 11]
Testing with list
["1", "5", "2", "4", "3", "6", "4", "7", "5", "8", "6", "3", "9", "5", "3"]
As integers: [1, 5, 2, 4, 3, 6, 4, 7, 5, 8, 6, 3, 9, 5, 3]
Testing with list
["-5", "-4", "-1", "-2", "-3", "-6", "-7"]
As integers: [-5, -4, -1, -2, -3, -6, -7]
Testing with list
["-30", "27", "-21", "-93", "-24", "-4", "-26", "66", "82", "-14", "-60", "88", "-94", "10", "-49", "58", "-49", "-75"]
As integers: [-30, 27, -21, -93, -24, -4, -26, 66, 82, -14, -60, 88, -94, 10, -49, 58, -49, -75]