arraylist到int?

rdlzhqv9  于 2021-07-14  发布在  Java
关注(0)|答案(3)|浏览(341)

我需要一些帮助,因为我对java不是很在行。我只需要返回长度为奇数的单词?但我犯了个错误。

import java.io.*;
import java.util.ArrayList;

public class ArrayListOdd {

     public static ArrayList<Integer> lengths(ArrayList<String> list) {
      ArrayList<Integer> lengthList = new ArrayList<Integer>();
      for (String s : list)
            lengthList.add(s.length());
        return lengthList;
     }
    public static void main(String args[])
    {
        ArrayList<String>  
        list = new ArrayList<String>();

        list.add("yoy");
        list.add("lmao");
        list.add("lol");
        list.add("kk");
        list.add("bbb");

        ArrayList<Integer> lengths = lengths(list);

        ArrayList oddList = new ArrayList();
        oddList = (ArrayList)list.clone();
        if (lengths % 2 != 0) {
        System.out.println("Strings with odd length are: " + oddList);
    }
  }
}
p4tfgftt

p4tfgftt1#

您正试图对列表执行整数运算。'“Length”是arraylist,操作%不适用于它。另外,我认为你不应该在这里使用克隆,而只是重复一下 list 并检查每个元素是否是奇数-打印它或添加到另一个列表如果是。

cbjzeqam

cbjzeqam2#

最好实现一个单独的方法来复制奇数长度的字符串:

public static List<String> oddLengths(List<String> list) {
    List<String> result = new ArrayList<>();
    for (String s : list) {
        if (s.length() % 2 != 0) {
            result.add(s);
        }
    }
    return result;
}

那就直接调用这个方法 main 方法:

List<String> list = new ArrayList<>();

list.add("yoy");
list.add("lmao");
list.add("lol");
list.add("kk");
list.add("bbb");

List<String> oddList = oddLengths(list);

System.out.println("Strings with odd length are: " + oddList);

效率较低的方法是复制初始列表,然后使用 removeIf 操作:

List<String> oddList2 = new ArrayList<>(list); // no need to use clone
oddList2.removeIf(s -> s.length() % 2 == 0); // removing all strings with even length
System.out.println("Strings with odd length are: " + oddList2);

使用带有过滤操作的流api可以方便地获得相同的结果:

public static List<String> oddLengths(List<String> list) {
    return list.stream()
            .filter(s -> s.length() % 2 != 0)
            .collect(Collectors.toList());
}
jc3wubiy

jc3wubiy3#

修改长度方法

public static void main(String []args){
         ArrayList<String>  
        list = new ArrayList<String>();

        list.add("yoy");
        list.add("lmao");
        list.add("lol");
        list.add("kk");
        list.add("bbb");

        ArrayList<String> lengths = lengths(list);

        System.out.println(lengths.toString());
     }

     public static ArrayList<String> lengths(ArrayList<String> list) {
      ArrayList<String> lengthList = new ArrayList<String>();
      for (String s : list)
            if(s.length() % 2 != 0)
               lengthList.add(s);
        return lengthList;
     }

相关问题