I would Like to convert some logic using Java8 Stream. How should we modify the code?
public boolean isBFOrder(final BFReturn pReturnRequest) {
ArrayList<BFReturnShip> shipGroupList =pReturnRequest.getShipGroupList();
Boolean bfOrder = false;
for(BFReturnShip bfReturnShip : shipGroupList) {
if(bfReturnShip.getModeOfReturn().equals(TYPE)) {
bfOrder = true;
} else {
return false;
}
}
return bfOrder;
}
return pReturnRequest.getShipGroupList()
.stream()
.allMatch(i -> i.getModeOfReturn().equals(REFUND_ONLY));
Provided that pReturnRequest.getShipGroupList() is never null.
As #Holger points out, we can improve the piece above by covering the case where the list comes empty.
final List<BFReturnShip> list = pReturnRequest.getShipGroupList();
return !list.isEmpty() &&
list.stream().allMatch(i -> i.getModeOfReturn().equals(REFUND_ONLY));
How do I check if the next element in the list is null ?
while(it.hasNext()){
System.out.println(it.next()+"\n");
}
this is how I tried, but when the last element is null it prints it as null.
I tried to change it
while(it.hasNext()){
if(it.next()==null){
}else
System.out.println(it.next()+"\n");
}
but this just makes it worst because some of the elements don't even print!
This is my Iteration method/anonymous class
public Iterator<Filmi> iterator3DFilms ()throws FilmiException{
if(filmList.isEmpty())
throw new FilmiException("No Films on the list");
return new Iterator<Filmi>(){
private int index=0;
public boolean hasNext(){
return index <filmList.size();
}
public Filmi next(){
Filmi lb = filmList.get(index++);
if(lb.is3D()== true)
return lb;
if(hasNext())
return next();
return null;
}
public void remove(){}
};
}
The null print only happens at the last element
Thank you.
Naturally, code like
if (it.next() == null){
} else {
System.out.println(it.next()+"\n");
}
will consume every other non-null element, as you are observing. Plus calling it.next() without checking it.hasNext() is a recipe for disaster.
Why not write
Foo/*ToDo - use the correct type here*/ foo = it.next()
if (foo != null){
/*ToDo*/
}
instead?
No it cannot work this way because if it.next() is not null you call it.next() twice which will make you skip a value that could not even be available.
Use a variable instead as next:
Object o = it.next();
if (o != null) {
...
}
you should use stream instead of iterator.
filmList.stream().filter(film->film!=null).filter(film->film.is3D())
Edit:
or, if you'r not in Java 8 :
Predicate<Film> isNotNullAnd3D = new Predicate<Person>() {
public boolean apply(Film f) {
return f != null && f.is3D();
}
};
Collection2.filter(filmList, isNotNullAnd3D)
You never mentioned why you use iterators explicitly in the first place.
Why not use implicit iterator notation like this ? :
for (Film film : filmList) {
if (film != null ){
....
}
}
Additionally to what others said: in case you are doing a for-each loop with a primitive type like int
for (int node : input) {
doSomething(node);
}
you might want to consider using the Wrapper class instead:
for (Integer node : input) {
if (node == null) throw new IllegalArgumentException();
doSomething(node);
}
I have a Set and I will check if an Object with the same property still exists. My first approach was to iterate over the list and check but I guess there is a better approach in Java 8. Does anyone have any suggestion how to check this in an elegant way?
final Set<UserSelected> preparedUserSelected = new HashSet<>();
UserSelected userSelected1 = new UserSelected();
userSelected1.setInstitutionId("1");
userSelected1.setUserId("1");
userSelected1.setChatMessageFilter(ChatMessageFilterEnum.TYP2);
UserSelected userSelected2 = new UserSelected();
userSelected2.setInstitutionId("2");
userSelected2.setUserId("2");
userSelected2.setChatMessageFilter(ChatMessageFilterEnum.TYP1);
UserSelected userSelected3 = new UserSelected();
userSelected3.setInstitutionId("3");
userSelected3.setUserId("3");
userSelected3.setChatMessageFilter(ChatMessageFilterEnum.TYP2);
preparedUserSelected.add(userSelected1);
preparedUserSelected.add(userSelected2);
preparedUserSelected.add(userSelected3);
UserSelected userSelectedToCheck = new UserSelected();
userSelectedToCheck.setInstitutionId("2");
userSelectedToCheck.setUserId("2");
userSelectedToCheck.setChatMessageFilter(ChatMessageFilterEnum.TYP1);
boolean contains = false;
for (final UserSelected userSelected : preparedUserSelected) {
if (userSelectedToCheck.getInstitutionId().equals(userSelected.getInstitutionId())
&& userSelectedToCheck.getUserId().equals(userSelected.getUserId())
&& userSelectedToCheck.getChatMessageFilter() == userSelected.getChatMessageFilter())
contains = true;
}
System.out.println("contains: " + contains);
You need to properly implement equals and hashCode methods in your UserSelected class. After that you can easily check the existence with preparedUserSelected.contains(userSelectedToCheck).
Here's sample implementation of equals/hashCode for your class:
#Override
public int hashCode() {
return Objects.hash(getUserId(), getInstitutionId(), getChatMessageFilter());
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null || getClass() != obj.getClass())
return false;
UserSelected other = (UserSelected) obj;
return Objects.equals(getChatMessageFilter(), other.getChatMessageFilter()) &&
Objects.equals(getInstitutionId(), other.getInstitutionId()) &&
Objects.equals(getChatMessageFilter(), other.getChatMessageFilter());
}
Try this anyMatch of Lambda Expression(Java 8).
Returns whether any elements of this stream match the provided predicate. May not evaluate the predicate on all elements if not necessary for determining the result. If the stream is empty then false is returned and the predicate is not evaluated.
boolean isExist = preparedUserSelected.stream()
.anyMatch(userSelected -> userSelected.getInstitutionId().equalsuserSelected.getInstitutionId());
I am trying to create class structure as in this example:
public class SubjectListStructure {
public String topic_id;
public String topic_title;
public String created_date;
public String avatar_url;
public String vote;
public String name_family;
}
Now, I want to create an ArrayList consisting of those objects:
ArrayList<SubjectListStructure> nSubjects = = new ArrayList<SubjectListStructure>();
But now I can't check if nSubjects is empty or have some data like with this code:
public static Boolean ContainsAllNulls(ArrayList<SubjectListStructure> arrList)
{
if(arrList != null)
{
for(SubjectListStructure a : arrList)
if(a != null) return false;
}
return true;
}
Or nSubjects.isEmpty() this solution and ContainsAllNulls(nSubjects) could not check correctly and return wrong result
First you should not allow nulls in the list. In this case simply List.isEmpty() will tell you if the list is empty.
If you can't or don't want to disallow nulls, your code works and properly tests if the list only contains nulls.
You don't even have to combine it with the isEmpty() method because the enhanced for works for empty lists and arrays too (in which case the body of the for will not be executed).
You can generalize your code to something like this which works for not just ArrayLists but for all Collections (lists, sets, etc.) and with any element type not just your custom SubjectListStructure type:
public static boolean emptyOrAllNulls(Collection<?> c) {
if (c != null)
for (Object o : c)
if(o != null)
return false;
return true;
}
Note that the enhanced for uses the Collection.iterator() to obtain an Iterator to walk over elements of the collection. In case of empty collections it is more efficient to first check if the collection contains any elements and not go through the iterator:
public static boolean emptyOrAllNulls(Collection<?> c) {
if (c != null && !c.isEmpty())
for (Object o : c)
if(o != null)
return false;
return true;
}
I trying to find whether the elements of 2 arrayLists are match or not.
But this code give me error Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException since some of the elements are null.
How can I solved this problem?
String level []={"High","High","High","High","High","High"};
ArrayList<Object> n = new ArrayList<Object>(Arrays.asList(level));
String choice []={null,"High","Low","High",null,"Medium"};
ArrayList<Object> m = new ArrayList<Object>(Arrays.asList(choice));
//Check if the two arrayList are identical
for(int i=0; i<m.size(); i++){
if(!(m.get(i).equals(n.get(i)))){
result= true;
break;
}
}
return result;
}
Just use Arrays.equals, like so:
String level []={"High","High","High","High","High","High"};
String choice []={null,"High","Low","High",null,"Medium"};
return Arrays.equals(level, choice);
The problem is that you are calling the equals method on some elements without first checking for null.
Change to:
for(int i=0; i<m.size(); i++){
if(m.get(i) != null && !(m.get(i).equals(n.get(i)))){
result = true;
break;
}
}
Or if you want to allow two null values to compare equal:
for(int i=0; i<m.size(); i++){
if (m.get(i) == null) {
if (n.get(i) != null) {
result = true;
}
} else if(!(m.get(i).equals(n.get(i)))){
result = true;
}
if (result) {
break;
}
}
One thing I don't get - why are you setting result to true when you find a mismatch? Don't you want to return true if both lists match and false otherwise?
The root of this problem could be you are using null as an actual value.
Just looking at your code you could use enum and instead of null use an EMPTY value. Then you can actually compare with in a list without nullpointerexceptions.
Check this out:
http://java.sun.com/docs/books/tutorial/java/javaOO/enum.html
Also try to avoid using arrays. Just use List but use the proper type. Don't use List<Object> that is almost never valid.
null should indicate an error or testing only. It should never be used in valid code as you will create null pointer exception bugs during runtime.
if you know the first list never contains nulls switch the call around
if(!(n.get(i).equals(m.get(i)))){
also specifying ArrayList<Object> is bad practice, use List<String> if it is actually String objects.
Check if the objects are the same object (or both null) first. Check for null before you do the equals() test.
boolean result = true;
String level[] = { "High", "High", "High", "High", "High", "High" };
ArrayList<String> n = new ArrayList<String>(Arrays.asList(level));
String choice[] = { null, "High", "Low", "High", null, "Medium" };
ArrayList<String> m = new ArrayList<String>(Arrays.asList(choice));
// Check if the two arrayList are identical
for (int i = 0; i < m.size(); i++) {
String mElement = m.get(i);
String nElement = n.get(i);
if (mElement == nElement) {
result = true;
} else if ((mElement == null) || (nElement == null)) {
result = false;
break;
} else if (!(m.get(i).equals(n.get(i)))) {
result = false;
break;
}
}
return result;
}
Rewrite your if like this in order to check for both double-nullity and single-nullity:
if((m.get(i) == null && n.get(i) == null) || (m.get(i) != null && !(m.get(i).equals(n.get(i)))))
Rather than solving this specific problem, give yourself a tool you can use over and again, e.g.:
public static final boolean areEqual(Object o1, Object o2) {
return o1 == null ? o2 == null : o1.equals(o2);
}
...in some handy utility class, then use that in your loop.
But of course, for this specific requirement, derivation has the right answer (use java.util.Arrays.equals(Object[],Object[])).
Remove NULLs
You can remove NULL values from your List objects before processing.
myList.removeAll( Collections.singleton( null ) );
The Collections class is a bunch of convenient utility methods. Not to be confused with Collection (singular), the interface that parents List and is implemented by ArrayList.
See this posting, Removing all nulls from a List in Java, for more discussion.