stream流遍历一个列表list,在遍历中找到list2中满足条件的值存入list
时间: 2023-02-14 21:48:29 浏览: 54
可以使用Java8的Stream API来遍历列表list, 并使用filter()方法来筛选符合条件的值, 然后使用forEach()方法来存储到另一个列表list2中. 示例代码:
```
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
List<Integer> list2 = new ArrayList<>();
list.stream().filter(i -> i > 2).forEach(list2::add);
```
这段代码会在list中遍历每一个元素, 筛选出大于2的元素, 然后存入list2中.
相关问题
java使用序列流完成存入2个学生信息到students.txt文件, 然后将其内容再读取出来, 使用我们的Stream流遍历学生的所有学号信息
您好!是的,ChitGPT是一个类似于ChatGPT的人工智能,由CSDN开发,与OpenAI的ChatGPT没有关系。
对于您的问题,可以通过以下代码来完成:
写入两个学生信息到students.txt文件:
```
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
List<String> studentList = new ArrayList<String>();
studentList.add("001-张三-男-22岁");
studentList.add("002-李四-女-20岁");
try {
FileOutputStream fos = new FileOutputStream("students.txt");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(studentList);
oos.close();
fos.close();
System.out.println("学生信息已写入文件!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
读取并遍历所有学号信息:
```
import java.io.*;
import java.util.*;
public class Main {
public static void main(String[] args) {
try {
FileInputStream fis = new FileInputStream("students.txt");
ObjectInputStream ois = new ObjectInputStream(fis);
List<String> studentList = (List<String>) ois.readObject();
ois.close();
fis.close();
System.out.println("学生信息读取成功,遍历所有学号信息:");
studentList.stream().forEach(student -> {
String[] info = student.split("-");
System.out.println(info[0]);
});
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
```
以上代码中,我们使用了ObjectOutputStream和ObjectInputStream来进行序列化和反序列化操作,通过Stream流遍历每个学生的学号信息。
希望能够帮助您解决问题,如果您有任何其他问题,请随时问我!
不能使用stream流,map中key和value互相转化,并将相同的vale值所对应的key存入到list集合中,
不使用`Stream`流的话,我们可以使用一个`HashMap`来保存值相同的键的列表,遍历原始`Map`的键值对,将相同值的键添加到对应的列表中,最后得到一个值为列表的`HashMap`。
下面是示例代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Integer> map = new HashMap<>();
map.put("apple", 1);
map.put("banana", 2);
map.put("orange", 1);
map.put("peach", 3);
Map<Integer, List<String>> result = new HashMap<>();
for (Map.Entry<String, Integer> entry : map.entrySet()) {
Integer value = entry.getValue();
String key = entry.getKey();
List<String> list = result.get(value);
if (list == null) {
list = new ArrayList<>();
result.put(value, list);
}
list.add(key);
}
System.out.println(result);
}
}
```
输出结果与上面的示例相同:
```
{1=[apple, orange], 2=[banana], 3=[peach]}
```
在这个例子中,我们首先创建了一个空的`HashMap`,然后遍历原始`Map`的键值对,对于每个键值对,我们获取它的值并将它作为`HashMap`的键,然后获取对应的列表,如果列表不存在,则创建一个新的空列表并将其添加到`HashMap`中。接着将当前键添加到列表中。最后得到一个值为列表的`HashMap`。