Search code examples
javajava-stream

How to return Stream objects?


** I have just started studying streams in java and I am stuck with this question. In the below code the main method of Fclass is given to me and I have to create a class Employee, it's constructor and getter methods and I also have to create a method "query" in Fclass which should return stream of those Employee objects which have same department name and salary greater than or equal to the input that will be given. I have written the code but when i am running it, it's not generating any output. Can someone tell me where am I going wrong? **

import java.util.*;
import java.util.stream.*;
class Employee{
private String n;
private String d;
private int s;
    public Employee(String name, String dep, int sal) {
        this.n = name;                  //define class Employee
        this.d = dep;
        this.s = sal;
    }
    public String getname() {
        return n;
    }
    public String getdep() {
        return d;
    }
    public int getsal() {
        return s;
    }
    public String toString() {
        return n+":"+d+":"+s+" ";
    }
}//define class Employee

class FClass{
    public static Stream<Employee> query(ArrayList<Employee> eList, String d, double s) {
        Stream<Employee> emp = eList.stream().filter(x->x.getdep()==d && x.getsal() >= s);
        return emp;
    }//define method query

    
 public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        var eList = new ArrayList<Employee>();
        eList.add(new Employee("Jack", "HR", 30000));
        eList.add(new Employee("Aria", "HR", 40000));
        eList.add(new Employee("Nora", "IT", 50000));
        eList.add(new Employee("Bella", "IT", 60000));
        eList.add(new Employee("Jacob", "IT", 70000));
        eList.add(new Employee("James", "HR", 80000));
        String d = sc.next();       //read department
        double s = sc.nextInt();    //read salary
        
        var st = query(eList, d, s);
        st.forEach(n -> System.out.println(n + " "));
    }
}

Solution

  • In your filter you compare Strings with ==:

    x.getdep()==d

    Please use x.getdep().equals(d) instead.