0

Is there a more elegant way to achieve by using java 8 or above the eighth version what's below?

 List<String> exampleList = List.of("test","test1");
 exampleList.stream().filter(s -> s.equals("test")).findFirst();

Thanks in advance

kamil wilk
  • 117
  • 7

2 Answers2

2

It depends on what exactly you want to do.

If you just want to check if "test" is in one of the elements, you could just use .contains():

List.of("test","test1").contains("test");

If you want to find the first element fitting a condition, you can omit creating the list and directly create a Stream:

Stream.of("test","test1").filter(s->"test".equals(s)).findFirst()

If you want to check if an element fitting the condition exist, you can use anyMatch:

Stream.of("test","test1").anyMatch(s->"test".equals(s))
dan1st
  • 12,568
  • 8
  • 34
  • 67
0

This is probably the best your going to get.

List<String> exampleList = List.of("test","test1");
exampleList.stream().filter("test"::equals).findFirst();

If its reused you can just make a method out of the 2nd line. Question has also already been answered here

duppydodah
  • 165
  • 1
  • 3
  • 17