java中的Stream流

Logback日志级别(从大到小)

1:error:错误

2:warn:警告

3:info:信息
4:debug:调试

5:trace:追踪(例如:追踪用户行为轨迹)

Stream流:

针对集合进行功能简化

Stream流通常结合Lambda表达式来使用

Stream流方法分类:

1:获取方法:获取流(创建一个流水线)

2:中间方法:在流水线进行操作(例如:过滤,截取)

3:终结方法:流水线上的操作结束了,要关闭流水线 

Stream流获取方法

单列集合:Collection[list,set]

可以使用Collection接口中的默认方法Stream()生成流

default Stream<E> stream()

Returns a sequential Stream with this collection as its source. 

Stream 流对象=单列集合对象.Stream();

 双列集合:Map(不能直接获取流对象)

间接获取流对象

先通过keyset()或entryset(),获取set集合

Stream 流对象=set集合对象.stream();

数组 :

Stream 流对象=Arrays.stream(数组);

多个同一类型元素:
使用Stream流中的静态方法,可以把同一种类型元素封装成Stream流对象

static <T> Stream<T> of(T... values)

运用可变参数

Stream 流对象=Stream.of(1,2,3); 

public class test {
    public static void main(String[] args) {
        //单列集合获取流对象
        List<String>list=new ArrayList<>();
        Collections.addAll(list,"java1","java2","java3","c++1","c++2");
        Stream<String> stream = list.stream();


        //map集合获取流对象
        HashMap<Integer,String>map=new HashMap<Integer, String>();
        map.put(1,"java1");
        map.put(2,"java2");
       // Set<Integer>set=map.keySet();
        //Stream<Integer>stream1=set.stream();

        Set<Map.Entry<Integer, String>> entries = map.entrySet();
        Stream<Map.Entry<Integer,String>>stream1=entries.stream();

        //数组获取流对象
        Integer []arr={1,2,3};//得用包装类型
        Stream<Integer> stream2 = Arrays.stream(arr);
        //Stream<Integer>stream2=Arrays.stream(arr);
        
        //同一类型获取流对象
        Stream<Integer> integerStream = Stream.of(1, 2, 3);

    }
}

Stream流中间方法:

过滤方法:

Stream<T> filter(Predicate<? super T> predicate)

Returns a stream consisting of the elements of this stream that match the given predicate.

public class test2 {
    public static void main(String[] args) {
        //单列集合获取流对象
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"java1","java2","java3","c++1","c++2");
       /* Stream<String> stream = list.stream();
        //获取所有java开头的元素,并打印

        *//*stream.filter(new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return s.startsWith("java");
            }
        });*//*
        Stream<String>stream1=stream.filter(s->s.startsWith("java"));//获取所有以java开头的元素
       *//* stream1.forEach(new Consumer<String>() {
            @Override
            public void accept(String s) {

            }
        });*//*
        //stream1.forEach(s-> System.out.println(s));//实例方法引用
        stream1.forEach(System.out::println);//打印*/

        //我们可以直接链式
        list.stream()
                .filter(s->s.startsWith("java"))
                .forEach(System.out::println);
    }
}

 截取方法:
Stream<T> limit(long maxSize)

截取指定参数个数的数据

public class test3 {
    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"java1","java2","java3","c++1","c++2");
        list.stream()
                .limit(4)//中间方法,只截取前四个元素
                .forEach(System.out::println);
        /*java1
                java2
        java3
        c++1*/
    }
}

跳过方法:

 Stream<T> skip(long n)

跳过指定参数个数的数据

list.stream()
                .skip(3)//中间方法,跳过n个元素
                .forEach(System.out::println);
       /* c++1
        c++2*/

 合取方法:
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

合并a,b两个流变成一个流

public class test4 {
    public static void main(String[] args) {
        List<String >list1=new ArrayList<>();
        Collections.addAll(list1,"java1","java2","java3");
        List<String>list2=new ArrayList<>();
        Collections.addAll(list2,"c++1","c++2");

        //获取两个流对象
        Stream<String> stream1=list1.stream();
        Stream<String>stream2=list2.stream();

        //合并
        Stream<String> concat = Stream.concat(stream1, stream2);
        concat.forEach(System.out::println);
        /*java1
                java2
        java3
        c++1
        c++2*/
    }
}

 去除方法:
Stream<T> distinct()

去除流中重复的元素,依赖(hashCode和equals方法)

假如流中存储的是自定义对象,要在对象中重写hashCode和equals方法

public class test5 {
    public static void main(String[] args) {
        List<String> list=new ArrayList<>();
        Collections.addAll(list,"java1","java1","java3","c++1","c++2");
        list.stream()
                .distinct()
                .forEach(System.out::println);
        /*java1
                java3
        c++1
        c++2*/
    }
}

 类型转换方法:

<R> Stream<R> map(Function<? super T,? extends R> mapper)

将流中元素类型进行转换

class People
{
    private String name;

    public People(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "People{" +
                "name='" + name + '\'' +
                '}';
    }
}
class Superman
{
    private String name;

    public Superman(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Superman{" +
                "name='" + name + '\'' +
                '}';
    }
}
public class test6 {
    public static void main(String[] args) {
      List<People>list=new ArrayList<>();
      list.add(new People("hhh"));//这里存的是People类型

      list.stream().map(new Function<People,Superman>() {
          @Override
          public Superman apply(People people) {
              return new Superman(people.getName());
          }
      })
              .forEach(System.out::println);//打印出来Superman类型,说明类型发生转换Superman{name='hhh'}
        list.stream()
                .map(people -> new Superman(people.getName()))
                .forEach(System.out::println);

    }
}

 排序方法:

Stream<T> sorted()

Stream<T> sorted(Comparator<? super T> comparator)

public class test7 {
    public static void main(String[] args) {
        List<Integer>list=new ArrayList<>();
        Collections.addAll(list,1,5,9,3,6);
        //使用sort排序
        list.stream()
                .sorted()//默认升序
                .forEach(System.out::println);

        /*list.stream()
                .sorted(new Comparator<Integer>() {
                    @Override
                    public int compare(Integer o1, Integer o2) {
                        return o2-o1;
                    }
                });*/
        list.stream()
                .sorted((o1,o2)->o2-o1)//降序
                .forEach(System.out::println);
    }
}

练习:
 

class Book
{
    private String name;

    public Book() {
    }

    public Book(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                '}';
    }
}
public class practice {
    public static void main(String[] args) {
        ArrayList<String>list1=new ArrayList<>();
        Collections.addAll(list1,"java1","java2","java3","java4","c++1","c++2");
        ArrayList<String>list2=new ArrayList<>();
        Collections.addAll(list2,"mysql1","mysql2","mysql3","oracle1","oracle2");
        //第一个队列只要名字是5个字符,且只要前三个
        Stream<String> stream1 = list1.stream()
                .filter(s -> s.length() == 5)
                .limit(3);
        //第二个队伍只要mysql,且跳过前两个
        Stream<String> stream2 = list2.stream()
                .filter(s -> s.startsWith("mysql"))
                .skip(2);

        //把两个队伍合并起来
        Stream<String>stream=Stream.concat(stream1,stream2);

        //把stream中的内容变成Book类
        Stream<Book> bookStream = stream.map(s -> new Book(s));

        //验证:
        bookStream.forEach(System.out::println);
       /* Book{name='java1'}
        Book{name='java2'}
        Book{name='java3'}
        Book{name='mysql3'}*/

    }
}

Stream流的终结方法:


void forEach(Consumer<? super T> action)

Performs an action for each element of this stream.

对此流的每个元素进行操作

Optional<T> min(Comparator<? super T> comparator)

Returns the minimum element of this stream according to the provided Comparator. This is a special case of a reduction.

返回此流中最小元素 

Optional<T> max(Comparator<? super T> comparator)

Returns the maximum element of this stream according to the provided Comparator. This is a special case of a reduction.

 返回此流中最大元素 

long count()

Returns the count of elements in this stream. 

返回此流中的元素数 

public class test8 {
    public static void main(String[] args) {
        ArrayList<Integer>list=new ArrayList<>();
        Collections.addAll(list,2,8,5,3,9);
        //求最小值
        System.out.println(list.stream()
                .min((o1, o2) -> o1 - o2));//返回的是排序后坐标最小的

        System.out.println(list.stream()
                .max((o1, o2) -> o1 - o2));//返回的是排序后坐标最大的

        //求流中偶数的个数
        long count=list.stream()
                .filter(i->i%2==0)
                .count();
        //count()是终结方法,想再次使用必须重新创建
    }
}

 Stream流中的收集方法:


<R,A> R collect(Collector<? super T,A,R> collector)

把流中的数据收集到集合中

 <A> A[] toArray(IntFunction<A[]> generator)

把流中的数据收集到数组中

public class test9 {
    public static void main(String[] args) {
        ArrayList<Integer>list=new ArrayList<>();
        Collections.addAll(list,1,2,3,4,5,6,7,8,9);

        List<Integer> collect = list.stream()
                .filter(i -> i % 2 == 0)
                .collect(Collectors.toList());//收集流中数据到List集合
        System.out.println(collect);

       Integer[]arr= list.stream()
                .filter(i->i%2==0)
                .toArray(value-> new Integer[value]);//value是数组的大小
        System.out.println(Arrays.toString(arr));

    }
}

 

public class test10 {
    public static void main(String[] args) {
        ArrayList<String>list=new ArrayList<>();
        Collections.addAll(list,"hhh,18","xxx,20","ccc,38");
        //获取年龄大于20岁的,并将其存到Map集合
       /* list.stream()
                .filter(s->{
                    String[] split = s.split(",");
                    Integer age=Integer.parseInt(split[1]);
                    return age>=20;
                });*/
       /* list.stream()
                .filter(s->Integer.parseInt(s.split(",")[1])>=20)
                .collect(Collectors.toMap(new Function<String, Object>() {

                    @Override
                    public Object apply(String s) {
                        return null;
                    }
                }))*/
        Map<String, String> map = list.stream()
                .filter(s -> Integer.parseInt(s.split(",")[1]) >= 20)
                .collect(Collectors.toMap(s -> s.split(",")[0], s -> s.split(",")[1]));
        System.out.println(map);//{ccc=38, xxx=20}

    }
}

  • 28
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
JavaStreamJava8引入的一个新特性,用于处理集合和数组等数据源的元素。它是一种函数式编程风格的API,可以通过链式调用一系列的操作来实现对数据源的处理,包括过滤、映射、排序、聚合等操作。 Stream分为间操作和终止操作两种类型。间操作是指对数据源进行的转换操作,每次间操作都会返回一个新的Stream对象,可以链式调用多个间操作。终止操作是指对数据源进行的最终操作,会返回一个非Stream类型的结果,例如forEach、count、collect等。 以下是一个简单的示例,演示如何使用Stream对一个整数列表进行过滤、映射和统计操作: ```java List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // 过滤出偶数 List<Integer> evenNumbers = numbers.stream() .filter(n -> n % 2 == 0) .collect(Collectors.toList()); // 将偶数加倍 List<Integer> doubledNumbers = evenNumbers.stream() .map(n -> n * 2) .collect(Collectors.toList()); // 统计偶数的个数 long count = evenNumbers.stream().count(); ``` 在上面的示例,我们首先创建了一个整数列表numbers,然后使用stream()方法将其转换为一个Stream对象。接着使用filter()方法过滤出偶数,并使用collect()方法将结果转换为一个List对象。然后使用map()方法将偶数加倍,并再次使用collect()方法将结果转换为一个List对象。最后使用count()方法统计偶数的个数。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

落落落sss

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值