简体   繁体   English

如何将 object 列表转换为 Java 中的 integer 列表?

[英]How to convert a list of object to a list of integer in Java?

I have a inner list of object into a list and I want to convert it in a list of Integer, because I know that its elements are Integer.我有一个 object 的内部列表,我想将其转换为 Integer 的列表,因为我知道它的元素是 Integer。

List<List<Object>> valuesModel = FCSMs.get(0).getValues();
            for (List<Object> innerList : valuesModel) {

//CONVERT LIST OF OBJECT TO LIST OF INTEGER

}

How Can I do?我能怎么做?

For a start it's a good practice to double check that you are in fact dealing with a list of type Integer.首先,最好仔细检查您是否确实在处理 Integer 类型的列表。 You may know that the only input is of that type, but anyone in the future working with your code will not (because it is not typed with Integer).您可能知道唯一的输入是该类型,但将来使用您的代码的任何人都不会(因为它不是用整数输入的)。 After that you can simply "cast" it to type Integer.之后,您可以简单地将其“转换”为类型 Integer。 Some pseudo code on how to do that can be found below:关于如何做到这一点的一些伪代码可以在下面找到:

List<List<Integer>> result = new ArrayList<>();
for (List<Object> innerList : valuesModel) {
    List<Integer> integerList = new ArrayList<>();
    for (Object object : innerList) {
        if (object instanceof Integer) {
            integerList.add((Integer) object);
        }
    }
    result.add(integerList);
}

You can do it like this.你可以这样做。 Since you know that all objects are Integers, no checks are done to avoid ClassCastExceptions.由于您知道所有对象都是整数,因此不会进行任何检查来避免 ClassCastExceptions。

  • Stream the list of lists to a stream of lists. Stream 列表列表为 stream 列表。
  • Then flatten those lists into a stream of object.然后将这些列表展平为 object 的 stream。
  • cast the object to an Integer.将 object 转换为 Integer。
  • and collect into a List并收集到一个列表中
List<List<Object>> valuesModel = List.of(List.of(1,2,3,4), List.of(5,6,7,8));

List<Integer> integers = valuesModel.stream()
           .flatMap(Collection::stream)
            .map(ob->(Integer)ob)
             .collect(Collectors.toList());

System.out.println(integers);

Prints印刷

[1, 2, 3, 4, 5, 6, 7, 8]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM