public class test01 {
public static void main(String[] args) {
System.out.println(" ");
System.out.println("Test:stream收集为set");
List<String> kk=new ArrayList<>();
kk.add("hahah");
kk.add("hahah");
kk.add("kkkk");
Set<String> collect2 = kk.stream().map(String -> String).collect(Collectors.toSet());
for (String s : collect2) {
System.out.println(s);
}
System.out.println(" ");
System.out.println("Test:stream收集为set,list,Map集合");
List<streamVo> list=new ArrayList<>();
list.add(new streamVo("hello",5));
list.add(new streamVo("java",4));
list.add(new streamVo("world",6));
Set<Integer> collect = list.stream().map(streamVo -> streamVo.val).collect(Collectors.toSet());
List<String> collect1 = list.stream().map(streamVo -> streamVo.attr).collect(Collectors.toList());
Map<Integer, String> collect3 = list.stream().collect(Collectors.toMap(streamVo -> streamVo.val, streamVo -> streamVo.attr));
Set<Map.Entry<Integer, String>> entries = collect3.entrySet();
for (Map.Entry<Integer, String> entry : entries) {
System.out.println(entry.getKey()+entry.getValue());
}
System.out.println(" ");
System.out.println("Test:Stream的遍历操作");
list.stream().forEach(streamVo -> {
System.out.println("***************");
System.out.println(streamVo.attr);
System.out.println(streamVo.val);
});
System.out.println(" ");
System.out.println("Test:Stream的过滤操作");
List<streamVo> collect4 = list.stream().filter(streamVo -> streamVo.val > 5).collect(Collectors.toList());
collect4.stream().forEach(streamVo -> {
System.out.println("***************");
System.out.println(streamVo.attr);
System.out.println(streamVo.val);
});
}
private static class streamVo{
String attr;
Integer val;
public streamVo(String attr,Integer val){
this.attr=attr;
this.val=val;
}
}
}
Stream流的使用学习
最新推荐文章于 2024-11-02 15:22:06 发布
本文通过实例展示了如何使用Java 8的Stream API将List转换为Set,以及对集合进行过滤、收集和映射操作。包括对String列表和streamVo对象的处理,演示了Stream在集合操作中的强大功能。
摘要由CSDN通过智能技术生成