-1

I was having some problem when trying to get the first array item out of Optional. Following as my code:

String[] temp = new String[2];
temp[0] = "email1";
temp[1] = "email2";
Optional<String[]> email = Optional.of(temp);
System.out.println(email.map(e -> e.get(0)).orElse(null));

I am trying to get the first email, otherwise just return as null. However, when I run this, I am getting these error messages:

System.out.println(email.map(e -> e.get(0)).orElse(null));
                                       ^
symbol:   method get(int)
location: variable e of type String[]
1 error

When I tried to do this:

System.out.println(email.stream().findFirst().get());

It prints out weird value:

[Ljava.lang.String;@7adf9f5f

Any ideas? Thanks!

QWERTY
  • 2,303
  • 9
  • 44
  • 85
  • 2
    Semi-related, but you should ask yourself how an empty Optional is different from a zero-element array. Are you actually treating them differently? It's definitely possible you are — but if all of your non-empty Optionals are of arrays with at least one element (as it sounds like they are, since you're not checking the array length within your `map` lambda), then the most natural way to represent that could just be a "naked" `String[]` (not wrapped in an Optional), which you then check for `temp.length > 0`. (You can search "java collection optional" for more details and insights.) – yshavit Feb 18 '23 at 05:43
  • Oh, and as for "it prints out a weird value": https://stackoverflow.com/q/29140402/1076640 – yshavit Feb 18 '23 at 06:00

2 Answers2

1

Arrays don't really have methods, per se. .get is something you call on a Collection, not a primitive array. Since the Optional contains an actual, primitive Java array, just use brackets [] to access the element.

System.out.println(email.map(e -> e[0]).orElse(null));
Silvio Mayolo
  • 62,821
  • 6
  • 74
  • 116
  • Is there any way I can use the second approach to get the value? the .stream().findFirst() – QWERTY Feb 18 '23 at 05:38
  • I'm not sure I understand what you're trying to do with a stream. an `Optional` is a stream of zero or one objects. `.stream` doesn't return a stream of the underlying data, it returns a stream whose *element* is the underlying data. You could [flatten](https://docs.oracle.com/en/java/javase/16/docs/api/java.base/java/util/stream/Stream.html#flatMap(java.util.function.Function)) the nested stream, but that's far less clear than just getting the element from the array in the first place. – Silvio Mayolo Feb 18 '23 at 05:40
  • I am trying to achieve the same thing but instead of using the .map to get first element, I wanted to use the findFirst() – QWERTY Feb 18 '23 at 05:41
  • 1
    It sounds like you may want Streams ([`Stream.of(temp)`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/stream/Stream.html#of(T...))) rather than Optionals. – yshavit Feb 18 '23 at 05:46
  • No no it should be Optional because it may be null. I am just extracting out the portion to make the question simpler – QWERTY Feb 18 '23 at 05:47
  • 1
    I think you're misunderstanding the point of `Optional`. If you want to stream over some data, then you want `Stream.of`. `Optional` isn't a magic wand you wave to eliminate the null problem in Java. – Silvio Mayolo Feb 18 '23 at 05:49
  • You _could_ do something like `Optional.of(temp).map(Stream::of).orElse(Stream.empty()).findFirst()`... but that's a lot of hoops for what would otherwise be a couple pretty straightforward checks (one for null, one for length). What that chain does is: turn your maybe-null array into an `Optional`, then maps that to an `Optional>`, then gets that stream or an empty one if the Optional was empty, and then tries to get the first element from that stream. I would not suggest this. – yshavit Feb 18 '23 at 05:52
  • 1
    `Optional.of(temp).filter(a -> a.length != 0).map(e -> e[0])` or `Stream.ofNullable(temp).flatMap(Arrays::stream).findFirst()` In either case, there’s no need to switch between `Optional` and `Stream` API. And there’s no point in using an `Optional` “because it may be null”, followed by calling `get()` unconditionally. – Holger Feb 20 '23 at 15:03
0

An Optional works alike an if-else test but lay out inside a special object to carry a value and make comparison to an equivalent

You put an "array" as a value into the Optional, the only object get() could return is the array not any of it's elements, also, get() for Optional does not take an argument in it.

The isPresent() boolean and the void ifPresent(ConsumerAndItsValue cmv) methods are a test to find if the "VALUE" is present, works much more like comparing using if object.equals(this object)

So of you want to use it for particular email addresses you simply put in each string , the tests cannot see into the array, those elements are more objects.

Create a java.util.Consumer≪Anobject> the functional code assigned "to a lambda", Anobject should be the type in accept method accept(T to) method. Here's a stack overflow page I found Proper usage of Optional.ifPresent()

And it is possible to iterate over an array contents (external site example). https://mkyong.com/java8/java-8-consumer-examples/

Samuel Marchant
  • 331
  • 2
  • 6