---
title: "Stream - Find"
author: "fairy_xzc"
date: "2018-06-19T21:51:12Z"
tags: []
categories: ["编程语言"]
slug: "stream-find"
draft: false
lastmod: "2018-06-19T22:03:46Z"
id: 2425205
url: "https://agilestyle.iteye.com/blog/2425205"
---

**原创转载请注明出处：[http://agilestyle.iteye.com/blog/2425205](/blog/2425205)**

 

## optional.get

```
private static void optionalGetTest() {
    Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

    Optional<Integer> optional = stream.filter(i -> i % 2 == 0).findAny();

    System.out.println(optional.get());
}
```

Console Output

```
2
```

  

## optional.orElse

```
private static void optionalOrElseTest() {
    Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

    Optional<Integer> optional = stream.filter(i -> i > 10).findAny();

    System.out.println(optional.orElse(-1));
}
```

 Console Output

```
-1
```

 

## optional.ifPresent

```
private static void optionalIfPresentTest() {
    Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

    Optional<Integer> optional = stream.filter(i -> i % 2 == 1).findFirst();

    optional.ifPresent(System.out::println);
}
```

Console Output

```
1
```

  

## optional.isPresent

```
private static void optionalIsPresentTest() {
    Stream<Integer> stream = Arrays.stream(new Integer[]{1, 2, 3, 4, 5, 6, 7});

    Optional<Integer> optional = stream.filter(i -> i % 2 == 0).findFirst();

    boolean result = optional.isPresent();
    System.out.println(result);
}
```

Console Output

```
true
```