length of each element in an array Java

后端 未结 5 485
不思量自难忘°
不思量自难忘° 2021-01-29 15:41

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         


        
相关标签:
5条回答
  • 2021-01-29 16:19

    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());
    }
    
    0 讨论(0)
  • 2021-01-29 16:25

    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.

    0 讨论(0)
  • 2021-01-29 16:36

    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;
    }
    
    0 讨论(0)
  • 2021-01-29 16:46

    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.

    0 讨论(0)
  • 2021-01-29 16:46

    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;
    }
    
    0 讨论(0)
提交回复
热议问题