-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
  • 8,084
  • 8
  • 48
  • 62
rohit12sh
  • 827
  • 2
  • 11
  • 24

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,962
  • 7
  • 39
  • 59
  • 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