Here is what I\'m trying to use. The method .length doesn\'t work for anything I try, so I\'m not even sure where to begin.
import java.util.ArrayList;
public c
For Java 8 user
public static void main(final String[] args) {
List<String> strings = Arrays.asList("Hi", "Hello", "how r u?");
List<Integer> lengthList = lengths(strings);
lengthList.forEach(System.out::println);
}
public static List<Integer> lengths(List<String> list) {
return list.stream().mapToInt(s -> s.length()).boxed()
.collect(Collectors.toList());
//OR
return list.stream().mapToInt(String::length).boxed()
.collect(Collectors.toList());
}
In the following code:
ArrayList<Integer> lengthList = new ArrayList<Integer>();
for (int nums: lengthList) {
System.out.println(nums.length());
}
You are creating an ArrayList<Integer> lengthList
which is empty and trying to iterate over it.
I think you want to iterate over list
something like this:
for (String s: list) {
lengthList.add(s.length());
System.out.println(s.length());
}
and add length()
of each String
to lengthList
in each iteration.
Here in your code you need to update at 2 places:
1) In lengths method you are passing list(ArrayList<String> list
), but you are not iterating over that you. You have to iterate over this list.
2) In the for loop you have made the variable as int, while the list is of type String. So update your code like below :
public static ArrayList<Integer> lengths(ArrayList<String> list) {
for (String nums: list) {
System.out.println(nums.length());
}
return lengthList;
}
You are trying to iterate through a single int
instead of the strings array. Change
for (int nums: lengthList) {
System.out.println(nums.length());
}
to
for (String str: list) { // loop through the list of strings
lengthList.add(str.length()); // store the individual length of each string
}
so as to loop through the list of strings, collect the length
of each string & store it int the Arraylist
that you return
later.
Use following code:
public static List<Integer> lengths(List<String> list) {
List<Integer> lengthList = new ArrayList<Integer>();
for (String nums: list) {
int len = nums.length();
lengthList.add(len);
System.out.println(len);
}
return lengthList;
}