length of each element in an array Java

后端 未结 5 488
不思量自难忘°
不思量自难忘° 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 strings = Arrays.asList("Hi", "Hello", "how r u?");
      List lengthList = lengths(strings);
      lengthList.forEach(System.out::println);
    }
    
    public static List lengths(List list) {
    
     return list.stream().mapToInt(s -> s.length()).boxed()
        .collect(Collectors.toList());
    //OR
    return list.stream().mapToInt(String::length).boxed()
        .collect(Collectors.toList());
    }
    

提交回复
热议问题