-1

I have the sample code below

String value="xyz";
dataList.stream().filter(obj -> obj.equals(value))

My question is: how to have the value available in my lambda expression in Filter.

Vadim Kotov
  • 7,766
  • 8
  • 46
  • 61
rohit12sh
  • 735
  • 2
  • 9
  • 21

1 Answers1

1

It is directly accessible if you are using Java 8, see the below code.

 public static void main(String args[]) {
        String value="xyz";
        List<String> dataList = new ArrayList<>();
        dataList.add("abc");
        dataList.add("def");
        dataList.add("ghi");
        dataList.add("xyz");
        dataList.add("jkl");
        dataList.add("mno");



        dataList.stream().filter(obj -> obj.equals(value)).forEach(System.out::println);
    }
Mohit Kanwar
  • 2,785
  • 6
  • 36
  • 56
  • Thanks! Actually, Eclipse was giving me compilation error as I was typing the variable name in my lambda expression. Its good now! – rohit12sh Feb 27 '18 at 11:01
  • okay. may be it was because of language level not set to Java 8 earlier. – Mohit Kanwar Feb 27 '18 at 11:02
  • 2
    @rohit12sh Maybe you changed `value` later. Lambdas can use only use variables which are either declared as `final` or are *effectively* final (they don't change). – Pshemo Feb 27 '18 at 11:21