java 8 streams filter by list over list - java-8

I need to filter condition by firstname and lastname in the List of names present in either official or unOfficial names List and return List of EmployeeDetails.
Below are the pojo classes
public class EmployeeDetails {
private NameDetails nameDetails;
public NameDetails getNameDetails() {
return nameDetails;
}
public void setNameDetails(NameDetails nameDetails) {
this.nameDetails = nameDetails;
}
}
public class NameDetails {
private List<Name> officalName;
private List<Name> unOfficialName;
public List<Name> getOfficalName() {
return officalName;
}
public void setOfficalName(List<Name> offiicalName) {
this.officalName = offiicalName;
}
public List<Name> getUnOfficialName() {
return unOfficialName;
}
public void setUnOfficialName(List<Name> unOfficialName) {
this.unOfficialName = unOfficialName;
}
}
public class Name {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
I tried for filtering with list of officialNames and it is working fine,but I also want to filter names present in unOfficial Names also.(OR Condition)
return employeeDetailList.stream().filter(employeeDetails->(employeeDetails.getNameDetails().getOffiicalName()).stream()
.anyMatch(name-> (null!=name) && (firstName).equals(name.getFirstName()) && (lastName).equals(name.getLastName())))
.collect(Collectors.toList());
Help me to solve the issue.Thanks

If you can't override equals/hashCode (if you could there would be a faster way), then:
employeeDetailList
.stream()
.filter(x -> Stream.concat(
x.getNameDetails().getOfficalName().stream(),
x.getNameDetails().getUnOfficialName().stream()
)
.anyMatch(y -> Objects.equals(y.getFirstName(), firstName) &&
Objects.equals(y.getLastName(), lastName)))
.collect(Collectors.toList());

Just add the OR condition:
return employeeDetailList.stream().filter(employeeDetails->
((employeeDetails.getNameDetails().getOffiicalName()).stream().anyMatch(name-> (null!=name) && (firstName).equals(name.getFirstName()) && (lastName).equals(name.getLastName()))))
|| ((employeeDetails.getNameDetails().getUnOfficialName()).stream().anyMatch(name-> (null!=name) && (firstName).equals(name.getFirstName()) && (lastName).equals(name.getLastName()))))
.collect(Collectors.toList());

Related

Return an empty object Java Spring Boot REST

I'm writing a dto class containing the information of a user
public class User {
private String firstName;
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
I'd receive this JSON object if I do GET api/v1/user/1
{
firstName: John,
lastName: Kennedy
}
But when the firstName and the lastName are null, I want to receive an empty object like:
{}
How would you do technically on Spring Boot in order to receive such empty object in Json format?
Thank you in advance
You could try to annotate your class with:
#JsonInclude(Include.NON_NULL)
If you want an empty object { } and empty request is not valid for you, you can create an auxiliar class called EmptyObject or something similar:
#JsonSerialize
public class EmptyObject {
}
And into your controller:
return user.getFirstName() == null && user.getLastName() == null ?
ResponseEntity.ok(new EmptyObject()) : ResponseEntity.ok(user);

Springdoc cannot detect POJO's fields to map as individual parameters on UI

My springboot application has a #RestController which takes a POJO class as parameter.
#GetMapping(path="/")
public void sayHello(Person person) {
System.out.println(person);
}
and here's the definition of Person class which is just a POJO.
public class Person {
private String firstName;
private String lastName;
private int age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
#Override
public String toString() {
return "Person [firstName=" + firstName + ", lastName=" + lastName + ", age=" + age + "]";
}
}
This is how springdoc-ui interprets it for showing parameters in UI.
I did not use #RequestBody in the controller yet springdoc assumes the input to be in the form of JSON body. I intend it to be as query parameters as below
Interestingly if I change the swagger implementation to springfox, each fields of the POJO is interpreted as individual parameters in the UI by default. The last screenshot was taken using springfox implemntation. How do I get the same behavior with springdoc?
Using #ParameterObject fixes this.
#GetMapping(path="/")
public void sayHello(#ParameterObject Person person) {
System.out.println(person);
}
Found the solution here:
https://github.com/springdoc/springdoc-openapi/issues/162
https://github.com/springdoc/springdoc-openapi/pull/505

Spring mongo repository sort descending by a certain property

I want to sort Descending by lastChange property, the List of items from mongo.
RequestRepository interface:
public interface RequestRepository extends MongoRepository<Request, String> {
List<Request> findByUser(String id);
}
Request.java:
#Document(collection = "Requests")
public class Request {
#Id
private String id;
private String user;
private String username;
private String requestTitle;
private String requestMessage;
private boolean read;
private Date lastChange;
private Date requestDate;
private boolean isActiveRequest;
private boolean isPremiumRequest; //paid request
public Request() {}
public Request(
String user,
String requestTitle,
String requestMessage,
boolean read,
Date lastChange,
Date requestDate,
boolean isActiveRequest) {
this.user = user;
this.requestTitle = requestTitle;
this.requestMessage = requestMessage;
this.read = read;
this.lastChange = lastChange;
this.requestDate = requestDate;
this.isActiveRequest = isActiveRequest;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getRequestTitle() {
return requestTitle;
}
public void setRequestTitle(String requestTitle) {
this.requestTitle = requestTitle;
}
public String getRequestMessage() {
return requestMessage;
}
public void setRequestMessage(String requestMessage) {
this.requestMessage = requestMessage;
}
public boolean isRead() {
return read;
}
public void setRead(boolean read) {
this.read = read;
}
public Date getLastChange() {
return lastChange;
}
public void setLastChange(Date lastChange) {
this.lastChange = lastChange;
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public boolean isActiveRequest() {
return isActiveRequest;
}
public void setActiveRequest(boolean activeRequest) {
isActiveRequest = activeRequest;
}
public boolean isPremiumRequest() {
return isPremiumRequest;
}
public void setPremiumRequest(boolean premiumRequest) {
isPremiumRequest = premiumRequest;
}
}
In my code I have the following list:
List<Request> = RequestRepository.findByUser(userObj.getId());
I want to have the data from RequestRepository.findByUser(userObj.getId()); sorted DESCENDING by the property lastChange.
I have searched on StackOverflow, and found the following method to sort:
List<Request> findAllByOrderByUpdatedAtDesc();
but this does not work if I search by User.
What is the solution to search by User id and to sort by lastChange?
Thank you!
This should do it.
List<Request> findByUserOrderByLastChangeDesc(String user);
Update your question with proper details.

invalid hex number ora-01465

i have this query in my code. i am trying to isert a image into table in the last column(blob). it is showing invalid hex number. can anybody help me out of this?
#ManagedBean(name="userprofile",eager=true)
#SessionScoped
public class Profile {
#ManagedProperty("#{jdbcTemplate}")
public JdbcTemplate jdbcTemplate;
private String firstName,lastName,email,description;
private UploadedFile photo1;
private int contactNumber;
private String insertQry;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public UploadedFile getPhoto1() {
return photo1;
}
public void setPhoto1(UploadedFile photo1) {
this.photo1 = photo1;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getContactNumber() {
return contactNumber;
}
public void setContactNumber(int contactNumber) {
this.contactNumber = contactNumber;
}
public void insertProfile() throws Exception{
InputStream is=photo1.getInputstream();
System.out.println(is);
insertQry="insert into profile
values('"+getFirstName()+"','"+getLastName()+"','"+getContactNumber()+"',
'"+getEmail()+"','"+getDescription()+"','"+utl_raw.cast_to_raw(is)+"')";
System.out.println(insertQry);
int num=jdbcTemplate.update(insertQry);
System.out.println(num);
}
}
any kind of response is appreciated in advance.
This error:
invalid hex number ora-01465
means that your not sending an Hexa.
Solution:
Please try to convert InputStream to Hexa before insert image.

Accessing Subclass properties in a JavaFX TableView ObservableArrayList

I am trying to access getter properties in a subclass with a TableView in JavaFX. I have the following class:
public class PersonType implements Serializable {
private static final long serialVersionUID = 1L;
Person person;
short count;
public PersonType() {
}
public PersonType(Person person, short count) {
super();
this.person = person;
this.count = count;
}
public Person getPerson() {
return person;
}
public void setPerson(Person person) {
this.person = person;
}
public short getCount() {
return count;
}
public void setCount(short count) {
this.count = count;
}
Person is like this:
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
String firstName;
String lastName;
public Person() {
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
}
Okay - lastly we have the following:
#FXML
private TableColumn tcFirstName;
#FXML
private TableColumn tcLastName;
#FXML
private TableView tblPersonTypes;
ArrayList<PersonType> pType = new ArrayList<PersonType>();
//Can assume that pType here has say 5 entries, the point of this
//is I'm trying to get to the firstName, lastName properties of the
//PersonType in the TableView below like the following:
tcFirstName.setCellValueFactory(new PropertyValueFactory<String,String>("firstName"));
tcLastName.setCellValueFactory(new PropertyValueFactory<String,String>("lastName"));
//Populate Table with Card Records
ObservableList<PersonType> data = FXCollections.observableArrayList(pType);
tblPersonTypes.setItems(data);
And I'm unsure how with a list of PersonTypes I can tell the table columns that I want the firstName and lastName properties of the Person object contained within. I know I could create a new object, and have the "count" from PersonTypes, then the other properties of "firstName", "lastName" etc without having an object property of Person. Any help would be greatly appreciated.
-- EDIT --
Another way I thought to do this was using CellFactories - where I would pass in to the CellValueFactories the Person object, then set the CellFactory to return a String value (firstName for the first name column, etc). And it would look like this:
tcFirstName.setCellValueFactory(new PropertyValueFactory<Person,String>("person"));
tcFirstName.setCellFactory(new Callback<TableColumn<Person,String>,TableCell<Person,String>>(){
#Override
public TableCell<Person,String> call(TableColumn<Person,String> param) {
TableCell<Person,String> cell = new TableCell<Person,String>(){
#Override
public void updateItem(String item, boolean empty) {
if(item!=null){
setGraphic(new Label(item.getFirstName()));
}
}
};
return cell;
}
});
Try this:
tcFirstName.setCellValueFactory(new Callback<CellDataFeatures<PersonType, String>, ObservableValue<String>>() {
public ObservableValue<String> call(CellDataFeatures<PersonType, String> p) {
// p.getValue() returns the PersonType instance for a particular TableView row
if (p.getValue() != null && p.getValue().getPerson() != null) {
return new SimpleStringProperty(p.getValue().getPerson().getFirstName());
} else {
return new SimpleStringProperty("<No TC firstname>");
}
}
});
}

Resources