java stream流获取ID 转为list
时间: 2023-10-13 20:05:04 浏览: 45
可以使用stream的map方法将对象转化为ID,再使用collect方法将ID转化为list,代码示例如下:
```
List<Integer> idList = objectList.stream().map(Object::getId).collect(Collectors.toList());
```
其中,Object是实际对象的类型,getId()为获取ID的方法。
相关问题
stream() 转为map
stream() 转为 map 是 Java 8 中的一个常见操作,可以将一个 Stream 转换为一个 Map 对象。在这个过程中,我们可以使用 Collectors.toMap() 方法来实现这个转换。toMap() 方法接受两个参数,第一个参数是用于生成 Map 的键的函数,第二个参数是用于生成 Map 的值的函数。在这里,我们可以使用方法引用来指定这些函数。如果我们想要将 Stream 中的元素转换为 Map,我们需要指定一个键和一个值的函数。键函数将返回一个用于生成 Map 键的值,而值函数将返回一个用于生成 Map 值的值。在这里,我们可以使用 User 对象的 id 属性作为键,使用 User 对象本身作为值。下面是一些示例代码:
1.将 User 对象列表转换为 id 和 name 的 Map:
Map<Integer,String> userMap1 = userList.stream().collect(Collectors.toMap(User::getId,User::getName));
2.将 User 对象列表转换为 id 和 username 的 Map:
Map<Long, String> map = userList.stream().collect(Collectors.toMap(User::getId, User::getUsername));
3.将 User 对象列表转换为 id 和 User 对象本身的 Map:
Map<Integer,User> userMap2 = userList.stream().collect(Collectors.toMap(User::getId,User->User));
java List中元素对象的属性转List
抱歉,我能回答您的问题。将Java List中元素对象的属性转为List的方法,可以使用Java 8中的Stream API和Lambda表达式来实现。具体实现方式可以参考下面的示例代码:
假设我们有一个Person类,它包含id和name两个属性:
public class Person {
private int id;
private String name;
// getter and setter methods
}
现在我们有一个List<Person>列表,我们想从列表中提取所有人的id属性,可以使用下面的代码:
List<Person> personList = // initialize person list
List<Integer> idList = personList.stream()
.map(Person::getId)
.collect(Collectors.toList());
这里的map方法使用方法引用(Person::getId)来指定将Person对象映射为其id属性,最后通过collect方法将结果转换为List<Integer>。如果我们要提取其他属性,只需要将getId方法替换为对应属性的getter方法即可。