list<Obejct>转焕成List<String>
时间: 2023-10-14 16:22:50 浏览: 33
假设 Object 类中包含一个名为 `value` 的属性,可以使用 Java 8 的 Stream API 进行转换:
```java
List<Object> objectList = new ArrayList<>();
// 将 Object List 转换为 String List
List<String> stringList = objectList.stream()
.map(obj -> obj.getValue().toString())
.collect(Collectors.toList());
```
首先使用 `stream()` 方法将 List 转换成流,然后使用 `map()` 方法将每个 Object 对象转换成 String 类型,最后使用 `collect()` 方法将流转换成 List<String> 类型。
相关问题
List<List<String>> 转换成List<String>
List<List<String>> 转换成 List<String> 的方法是使用flatMap函数。flatMap函数将多个列表合并为一个列表。首先,我们可以使用stream()函数将List<List<String>>转换为Stream<List<String>>。然后,我们可以使用flatMap()函数将Stream<List<String>>转换为Stream<String>,并使用collect()函数将Stream<String>转换为List<String>。以下是示例代码:
List<List<String>> list = new ArrayList<>();
list.add(Arrays.asList("A", "B", "C"));
list.add(Arrays.asList("D", "E", "F"));
list.add(Arrays.asList("G", "H", "I"));
List<String> result = list.stream()
.flatMap(Collection::stream)
.collect(Collectors.toList());
System.out.println(result);
输出结果为:[A, B, C, D, E, F, G, H, I]
Collection<String>转成List<String>
Collection<String>转成List<String>可以通过以下方式实现:
1. 使用构造函数:
```
Collection<String> collection = new ArrayList<>();
List<String> list = new ArrayList<>(collection);
```
2. 使用addAll()方法:
```
Collection<String> collection = new ArrayList<>();
List<String> list = new ArrayList<>();
list.addAll(collection);
```
3. 使用Stream API:
```
Collection<String> collection = new ArrayList<>();
List<String> list = collection.stream().collect(Collectors.toList());
```
这些方法都可以将一个Collection<String>对象转换为List<String>对象。