【问题标题】:How to convert String[] that contains numbers to int[] in Java?如何在 Java 中将包含数字的 String[] 转换为 int[]?
【发布时间】:2017-12-05 17:00:19
【问题描述】:

我得到的是这条指令,它给了我一个 String[] 对象:

string.trim().split(" ");

使用Arrays.asList(string.trim().split(" "))的内容类似于:
[4, 3, 2, 5, -10, 23, 30, 40, -3, 30]

所以它的内容是由数字组成的。我想要的是将String[] 对象转换为int[] 对象。如果不将每个字符串都解析为 int,我该如何做到这一点?

【问题讨论】:

  • "如果不将每个字符串都解析为 int,我该怎么做?"你不能。在某些时候,它需要被解析(显式或隐式)。如果你想简化你的代码,你可以使用int[] intArr = Stream.of(strArray).mapToInt(Integer::parseInt).toArray();
  • 你可以做的是创建一个函数来手动将 String 转换为 int 但这会更糟
  • 我模棱两可抱歉。我的意思是不要直接使用 for 循环
  • 你在求魔法。无论您是编写一个还是隐含在流处理中,都需要一个循环。

标签: java arrays string casting


【解决方案1】:

你可以有点在没有循环的情况下这样做,但你只会得到List<Integer>而不是int[]

private static class IntegerAdapter extends AbstractList<Integer> implements List<Integer> {
    private final List<String> theList;

    public IntegerAdapter(List<String> strings) {
        this.theList = strings;
    }

    public IntegerAdapter(String[] strings) {
        this(Arrays.asList(strings));
    }

    @Override
    public Integer get(int index) {
        return Integer.parseInt(theList.get(index));
    }

    @Override
    public int size() {
        return theList.size();
    }
}

public void test(String[] args) {
    String test = "4 3 2 5 -10 23 30 40 -3 30";
    String[] split = test.split(" ");
    IntegerAdapter adapter = new IntegerAdapter(split);
    // Look ma! No loops :)
    System.out.println(adapter.get(4));
}

【讨论】:

    猜你喜欢
    • 2011-07-31
    • 2011-11-30
    • 1970-01-01
    • 2016-06-02
    • 2011-10-16
    • 2021-10-24
    相关资源
    最近更新 更多