In all the searching I did, I could not find an example of this sort. My bad :(
I have an Optional object containing an array. I now need to traverse the array and locate a particular element inside it.
Codes and sample classes as follows:
public class Component {
private String name;
public Component(String ipName) {
this.name = ipName;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
public class Container {
private Component[] componentArray;
public Container(Component[] ipComponentArray) {
this.componentArray = ipComponentArray;
}
public Component[] getComponentArray() {
return componentArray;
}
public void setComponentArray(Component[] componentArray) {
this.componentArray = componentArray;
}
}
public class TestClass {
public static void main(String[] args) {
Container newContainer = getNewContainer();
System.out.println(checkIfComponentIsPresent("Two", newContainer)); //prints true
System.out.println(checkIfComponentIsPresent("Five", newContainer)); //prints false
}
private static Container getNewContainer() {
return new Container(new Component[] {new Component("One"), new Component("Two"), new Component("Three")});
}
private static boolean checkIfComponentIsPresent(String ipName, Container newContainer) {
boolean isPresent = false;
Optional<Component[]> componentArrayOptional = Optional.ofNullable(newContainer).map(Container::getComponentArray);
if(componentArrayOptional.isPresent()) {
Component[] componentArray = componentArrayOptional.get();
if(componentArray != null && componentArray.length > 0) {
for(Component component : componentArray) {
if(ipName.equals(component.getName())) {
isPresent = true;
break;
}
}
}
}
return isPresent;
}
}
Can someone please advise me how can I improve the method checkIfComponentIsPresent? I want to know how can we traverse an array inside an Optional object, without converting it into a list or stream.
I can do it using streams as follows:
private static boolean checkIfComponentIsPresentUsingStreams(String ipName, Container newContainer) {
boolean isPresent = false;
Optional<Component[]> componentArrayOptional = Optional.ofNullable(newContainer).map(Container::getComponentArray);
if(componentArrayOptional.isPresent()) {
Stream<Component> componentArrayStream = Arrays.stream(componentArrayOptional.get());
isPresent = componentArrayStream.filter(component -> ipName.equals(component.getName())).findFirst().isPresent();
}
return isPresent;
}
But I cannot use streams, actually my classes are huge, and the array itself can contain numerous elements. Using streams, will degrade the performance.
Thanks!
Using streams, will degrade the performance, are you sure?