java8 Stream API一

//stream 的基本操作 map filter collect
public class StreamDemo1 {
private static List<Dish> menu = Arrays.asList(new Dish("鸡肉", false, 500), new Dish("鸭肉", false, 500),
new Dish("驴肉", false, 600), new Dish("鱼肉", false, 200), new Dish("狗肉", false, 800),
new Dish("牛肉", false, 520), new Dish("虾肉", false, 509));


public static void main(String[] args) {
demo4();
}


public static void demo1() {
List<String> words = Arrays.asList("hello", "world");
// distinct() 去重 获取去重后的集合
List<String[]> collect = words.stream().map(word -> word.split(" ")).distinct().collect(Collectors.toList());
String[] arr = collect.get(0);
for (String string : arr) {
System.out.println(string);
}
// Arrays::stream 数组变成流 flatMap 将各个生成的流扁平华为单个流
List<String> collect2 = words.stream().map(word -> word.split("")).flatMap(Arrays::stream).distinct()
.collect(Collectors.toList());


}


public static void demo2() {
// map 提取元素 filter 过滤
List<String> limit = menu.stream().filter(d -> d.getCalories() > 500).map(Dish::getName).limit(3)
.collect(Collectors.toList());
System.out.println(limit);
// sorted 排序
List<Dish> collect = menu.stream().sorted(new Comparator<Dish>() {
@Override
public int compare(Dish o1, Dish o2) {
return o1.getCalories() - o2.getCalories();
}
}).collect(Collectors.toList());
}


public static void demo3() {
List<OrderInfoResponse> resultList = Arrays.asList(new OrderInfoResponse("1", new Date()));


resultList.add(new OrderInfoResponse("3", new Date()));


resultList.add(new OrderInfoResponse("2", new Date()));
List<OrderInfoResponse> collect = resultList.stream()
.sorted((n1, n2) -> n2.getCreateTime().compareTo(n1.getCreateTime())).collect(Collectors.toList());


for (OrderInfoResponse orderInfoResponse : collect) {
System.out.println(orderInfoResponse);
}


}


public static void demo4() {
// 两个集合 重新组合 返回和可以被3整除的
List<Integer> num1 = Arrays.asList(1, 2, 3);
List<Integer> num2 = Arrays.asList(3, 4);


List<int[]> pairs = num1.stream().flatMap(i -> num2.stream().map(j -> new int[] { i, j }))
.collect(Collectors.toList());


pairs.forEach(action -> {
for (int[] ks : pairs) {
System.out.println(ks[0]);
}
});


}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值