I am trying to achieve an util as this in Spring Boot:
public static boolean isAllEmptyOrNull(Collection... collectionList) {
for (Collection collection : collectionList) {
if (!Collections.isEmpty(collection)) {
return false;
}
}
return true;
}
so I can handle cases as:
isAllEmptyOrNull(listOfCat);
isAllEmptyOrNull(listOfDog, mapOfStringToString);
isAllEmptyOrNull(listOfDog, listOfCat);
isAllEmptyOrNull(listOfDog, listOfCat, mapOfStringToList, mapOfStringToMap);
Any help will be sincerely appreciated :)
Updated 2018-12-06
Thanks for the help of #Deadpool, my solution turns out:
public static boolean isAllCollectionEmptyOrNull(Collection... collections) {
for (Collection collection : collections) {
if (!Collections.isEmpty(collection)) {
return false;
}
}
return true;
}
public static boolean isAllMapEmptyOrNull(Map... maps) {
for (Map map : maps) {
if (!Collections.isEmpty(map)) {
return false;
}
}
return true;
}
Of course, you can use stream and method overloading as nullpointer does.
No. You cannot create it as generic as you are looking for since a Map is not a Collection.
And of course Collection... collectionList signifies var args for Collection type.
The only way would be to break them into two separate stubs as :
public static boolean isAllEmptyOrNull(Collection... collectionList) {
return Arrays.stream(collectionList).allMatch(Collection::isEmpty);
}
public static boolean isAllEmptyOrNull(Map... maps) {
return Arrays.stream(maps).allMatch(Map::isEmpty);
}
You can have two different util methods one for to check Collection objects and another one for Map objects, since Map is not child of Collection interface
public static boolean isAllEmptyOrNull(Collection... collectionList) {
return Arrays.stream(collectionList).anyMatch(item->item==null || item.isEmpty());
}
public static boolean isAllEmptyOrNull(Map... maps) {
return Arrays.stream(maps).anyMatch(item->item==null || item.isEmpty());
}
To check all objects null or empty
public static boolean isAllEmptyOrNull(Collection... collectionList) {
return Arrays.stream(collectionList).allMatch(item->item==null || item.isEmpty());
}
public static boolean isAllEmptyOrNull(Map... maps) {
return Arrays.stream(maps).allMatch(item->item==null || item.isEmpty());
}
You can try this:
public static boolean isAllEmptyOrNull(Collection... collectionList) {
return Arrays.stream(collectionList).anyMatch(Collection::isEmpty);
}
Related
I want to implement matryoshka dolls.
If you open one doll, there will be a smaller one inside until a massive doll that does not contain any another doll.
My try:
public static class Puppe{
int massive;
Puppe contains;
public static boolean massiveOrNot(Puppe doll) {
if(doll.massive==0) return true;
else return false;
}
public static Puppe exchangeDoll(Puppe doll) {
Puppe newDoll=new Puppe();
doll=newDoll;
return doll;
}
}
I´m completly new to classes.
How can I save dolls within other dolls and for example count how many dolls are inside of one doll?
Best regards
sop
First thing get rid of static for now, you will need more of this objects.
Then you have to think about is your object going to contain.
public class Puppe{
Puppe container;
public boolean isContaining() {
if(container != null) return true;
return false;
}
public void setDoll(Puppe smallerOne) {
container = smallerOne;
}
public Puppe getDoll() {
if(container != null)
return container;
return nullptr;
}
}
I need to convert the method "contains()"
public boolean contains(List<Integer> list, int value){
for (int i : list) {
if(i == value)
return true;
into a method that can search for every datatype but i dont really know how to do it.
import java.util.List;
public class Search<T> {
public boolean contains(List<T> list, T value){
for ( T i : list) {
if(i == value)
return true;
}
return false;
}
}
This is my attempt so far but i dont know if this is all i have to do or not.
I hope someone can help me out.
There is already a method in List<T> that does that, List<T>::contains.
If you want to implement your own there are two ways to do it:
Same instance:
Here if the equals method hasn't been overridden it will return true if they are literally the same instance in memory.
public <T> boolean contains(List<T> list, T object){
for( T t : list){
if(t.equals(object))
return true;
}
return false;
}
Similar objects
Here you are forcing your T class to implement the Comparable interface, which contains a compareTo(o : Object) that returns 0 if they are similar.
public <T extends Comparable> boolean contains(List<T> list, T object){
for( T t : list){
if(t.compareTo(object) == 0)
return true;
}
return false;
}
Try equals instead of ==
import java.util.List;
public class Search<T> {
public boolean contains(List<T> list, T value){
for ( T i : list) {
if(i.equals(value))
return true;
}
return false;
}
}
when(validator.isValid(Sets.newHashSet("valid"))).thenReturn(true);
When validator.isValid(set) is invoked it returns false. It is because the validator implementation creates a new set that is different that the passed one (reference is different) - the items in both sets are same.
I need to return true if sets contains same items regardless of sets instances.
Something similar to org.mockito.Matchers:
public static <T> Set<T> anySetOf(Class<T> clazz) {
return (Set) reportMatcher(Any.ANY).returnSet();
}
except that I would pass instances not Class<T>.class.
And same for verify:
verify(validator, times(1)).isValid(Sets.newHashSet("valid"));
Is there such a matcher?
Apparently JB Nizet is right. There is no need for a specific matcher.
I have tried to use my own matcher and then after removal it worked also:
public static class SetItemMatcher extends ArgumentMatcher<Set<String>> {
public static Set<String> setOf(Set<String> items) {
return argThat(new SetItemMatcher(items));
}
private final Set<String> expected;
public SetItemMatcher(Set<String> expected) {
this.expected = expected;
}
#Override
public boolean matches(Object argument) {
Set<?> actual = (Set<?>) argument;
return actual.size() == expected.size() && containsAllItems(actual);
}
private boolean containsAllItems(Set<?> actual) {
for (Object o : actual) {
if (!expected.contains(o)) {
return false;
}
}
return true;
}
}
While Felix's answer is absolutely correct, I slightly modified it to cover more use-cases (i.e. covering any Collection with builder methods for Set and List):
Work with any collection, not just sets.
Added utility methods to create a list or set based on either just one item or another list/set
public class CollectionItemMatcher<T extends Collection> implements ArgumentMatcher<T> {
public static Set setOf(Object oneItem) {
return setOf(Sets.newHashSet(oneItem));
}
public static Set setOf(Collection items) {
return ArgumentMatchers.argThat(new CollectionItemMatcher<Set>(Sets.newHashSet(items)));
}
public static Set emptySet() {
return setOf(Sets.newHashSet());
}
public static List listOf(Object oneItem) {
return listOf(Lists.newArrayList(oneItem));
}
public static List listOf(Collection items) {
return ArgumentMatchers.argThat(new CollectionItemMatcher<List>(Lists.newArrayList(items)));
}
public static List emptyList() {
return listOf(Lists.newArrayList());
}
private final T expected;
public CollectionItemMatcher(T expected) {
this.expected = expected;
}
#Override
public boolean matches(T actual) {
return actual.size() == expected.size() && containsAllItems(actual);
}
private boolean containsAllItems(T actual) {
for (Object o : actual) {
if (!expected.contains(o)) {
return false;
}
}
return true;
}
}
Then you can do something like this:
verify(validator, times(1)).isValid(CollectionItemMatcher.setOf("valid"));
Hi guys i got this as an interview question and was having trouble with it. I am familiar with generics/collections & iterator but the manner i which the Collection is declared completely threw me.
Heres the question: Contained in the provided workspace is cocI, the start of a class that implements an Iterator that can be used to iterate a Collection of Collections. The Collection of Collections is passed into the constructor of the class. The Iterator should iterate through the contents depth-first.
For example, if the Collection of Collections looks like the following:
[0] – [“A”, “B”, “C”]
[1] – [“D”]
[2] – [“E”, “F”]
The iterator should then return the contents in the following order: “A”, “B”, “C”, “D”, “E”, “F”
Q.Provide implementations for the hasNext() and next() methods in cocI
Thanks
import java.util.Collection;
import java.util.Iterator;
public class cocI implements Iterator<Object> {
private Collection<Collection<Object>> _collOfColl = null;
public cocI(Collection<Collection<Object>> collofColl) {
_collOfColl = collofColl;
}
public boolean hasNext() {
// TODO implement this method
return false;
}
public Object next() {
// TODO implement this method
return null;
}
public void remove() {
throw new UnsupportedOperationException();
}
}
All you need to do is keep track of the current collection's iterator within the collection of collections. The hasnext() method, which is the tricky part, will then do one of two things: return true if the current iterator has more elements, if not search until we find a collection that has elements. If we exhaust all the collections, return false.
public class Cocl implements Iterator<Object> {
private Collection<Collection<Object>> _collOfColl = null;
private final Iterator<Collection<Object>> coClIterator;
private Iterator<Object> currentColIterator;
public Cocl(Collection<Collection<Object>> collofColl) {
_collOfColl = collofColl;
coClIterator = collofColl.iterator();
if (coClIterator.hasNext()) {
currentColIterator = coClIterator.next().iterator();
}
}
public boolean hasNext() {
if (currentColIterator == null) {
return false;
}
if (!currentColIterator.hasNext()) {
while (coClIterator.hasNext()) {
currentColIterator = coClIterator.next().iterator();
if (currentColIterator.hasNext()) {
return true;
}
}
return false;
} else {
return true;
}
}
public Object next() {
if (hasNext()) {
return currentColIterator.next();
}
throw new NoSuchElementException();
}
public void remove() {
throw new UnsupportedOperationException();
}
public static void main(String[] args) {
Collection<Object> one = Arrays.asList((Object) "A", (Object) "B", (Object) "C");
Collection<Object> two = Arrays.asList((Object) "D", (Object) "E");
Cocl cocl = new Cocl(Arrays.asList(one, two));
while (cocl.hasNext()) {
Object a = cocl.next();
System.out.println(a);
}
}
}
A couple of introductory remarks:
cocI is an odd class name; it should start with a capital letter.
The interface you are supposed to implement doesn't use generics effectively. You should be able to use a data type more specific than Object.
It is good practice to use the #Override annotation.
The solution involves an iterator for the outer collection and an iterator for the inner collection. When the inner iterator runs out of elements, it needs to be replaced with an iterator for the next collection. However, considering that a collection could be empty, the advancement needs to be done in a loop, which I've put in an advanceCollection() helper.
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;
public class cocI<T> implements Iterator<T> {
private Iterator<Collection<T>> outerIterator;
private Iterator<T> innerIterator;
public cocI(Collection<Collection<T>> collofColl) {
this.outerIterator = collofColl.iterator();
advanceCollection();
}
#Override
public boolean hasNext() {
return this.innerIterator != null && this.innerIterator.hasNext();
}
#Override
public T next() {
if (this.innerIterator == null) {
throw new NoSuchElementException();
}
try {
return this.innerIterator.next();
} finally {
advanceCollection();
}
}
#Override
public void remove() {
throw new UnsupportedOperationException();
}
private void advanceCollection() {
while ((this.innerIterator == null || !this.innerIterator.hasNext())
&& this.outerIterator.hasNext()) {
this.innerIterator = this.outerIterator.next().iterator();
}
}
}
There is one slightly tricky piece of code I used:
try {
return this.innerIterator.next();
} finally {
advanceCollection();
}
It is roughly equivalent to:
T result = this.innerIterator.next();
advanceCollection();
return result;
I have a class Polygon on which I wish to implement two iterators: one to run through all elements (vertices and edges in alternating order) just ONCE, and another to run through them ad infinitum (cyclically).
From a for-each usage standpoint, my guess is that I am only going to be able to have one of the above be the default iterator that can be used with for-each, via implementation of Iterable.iterator(). Is this correct? Or is there a way I could use for-each with both?
Just add two methods returning two different Iterators, one for each case:
public Iterable<String> eachOnce() {
List<String> allResults = new ArrayList<String>();
// fill list
return allResults;
}
public Iterable<String> eachCyclic() {
return new Iterable<String>() {
public Iterator<String> iterator() {
return new Iterator<String>() {
public boolean hasNext() {
return true;
}
public String next() {
// TODO implement
return null;
}
public void remove() {
// do nothing
}
};
}
};
}
This is just an example with a List of Strings, just adapt.
Instead of
for (Polygon p : polygons) { }
just use
for (Polygon p : polygons.eachOnce()) { }
or the cyclic edition
An answer I think is better than those already presented is a method that turns any Iterable into a cyclic one.
public class IterableUtils {
public static class CyclicIterator<T> implements Iterator<T> {
private final Iterable<T> inner;
private Iterator<T> currentIter;
public CyclicIterator(Iterable<T> inner) {
this.inner = inner;
}
public boolean hasNext() {
if (currentIter == null || !currentIter.hasNext()) {
currentIter = inner.iterator();
}
return currentIter.hasNext();
}
public T next() {
if (currentIter == null || !currentIter.hasNext()) {
currentIter = inner.iterator();
}
return currentIter.next();
}
public void remove() {
currentIter.remove();
}
}
public static <T> Iterable<T> cycle(final Iterable<T> i) {
return new Iterable<T>() {
public Iterator<T> iterator() { return new CyclicIterator<T>(i); }
};
}
}
Then you can just implement the single iterator method in the Polygon class and use
for (Element e: polygon) {
...
}
to iterate once and
for (Element e: cycle(polygon)) {
...
}
to iterate endlessly. As a bonus, the cycle modifier can be applied to any iterable.