public class StreamTest {
private static final List<Apple> appleList = new ArrayList<Apple>();
static {
appleList.add(new Apple(1, "red", 200, "河北"));
appleList.add(new Apple(2, "green", 500, "天津"));
appleList.add(new Apple(3, "red", 170, "山东"));
appleList.add(new Apple(4, "red", 280, "河北"));
appleList.add(new Apple(5, "green", 800, "河北"));
}
public static void main(String[] args) {
// 01、将list转化为stream
Stream<Apple> stream1 = appleList.stream();
// 02、stream转化回list
List<Apple> collect = stream1.collect(Collectors.toList());
// 03、peek处理器:获取流的每个对象并进行一些处理,这里的处理是输出每一条apple
System.out.println("==========3、peek处理器==========");
appleList.stream().peek(a -> {
a.setOrigin("dddddd");
System.out.println(a);
}).collect(Collectors.toList());
// 04、filter过滤器:对流中每个对象进行判断,不符合条件不通过
List<Apple> red = appleList.stream().filter(a -> a.getColor().equals("red")).collect(Collectors.toList());
// 05、map映射器,从Apple的流转化成其产地流
List<String> origin = appleList.stream().map(a -> a.getOrigin()).collect(Collectors.toList());
// 06、distinct去重
System.out.println("==========6、distinct去重==========");
List<String> originDistinct = appleList.stream()
.map(a -> a.getOrigin())
.distinct()
.peek(a -> System.out.println(a))
.collect(Collectors.toList());
// 07、debug
appleList.stream()
.filter(a -> a.getColor() != null)
.map(a -> a.getColor())
.distinct()
.peek(color -> System.out.println(color))
.toArray();
// 08.1、collect函数-将list流改造为map
Collector<Apple, ?, Map<Integer, Apple>> collector = Collectors.toMap(
a -> a.getId(), //新的map中的key
a -> a, //新的map中的value
(a1,a2) -> {
if (a1.weight>a2.weight) {
return a1;
}
return a2;
} // 如果两个apple是同一个key,那么value存放较大的apple
);
Map<Integer, Apple> map = appleList.stream().collect(collector);
// 50、remove
appleList.removeIf(apple -> apple.getId()!=1);
System.out.println("==========end==========");
}
}
@Data
class Apple {
int id;
String color;
int weight;
String origin;
public Apple(int id, String color, int weight, String origin) {
this.id = id;
this.color = color;
this.weight = weight;
this.origin = origin;
}
@Override
public String toString() {
return "Apple{" +
"id=" + id +
", color='" + color + '\'' +
", weight=" + weight +
", origin='" + origin + '\'' +
'}';
}
}
记录stream学习心得
于 2023-06-09 09:52:11 首次发布
本文展示了如何使用Java8的StreamAPI对列表进行操作,包括转换为Stream、使用peek处理器、filter过滤、map映射、distinct去重、debug、collect函数创建Map以及removeIf方法删除元素。示例中涉及Apple对象的属性如颜色、重量和产地。
摘要由CSDN通过智能技术生成