Use !isEmpty() instead of "size() > 0" or "size() != 0" (#1155)

* Use !isEmpty() instead of "size() > 0" or "size() != 0"

!isEmpty() expresses the intent more clearly and is therefore preferred.
Counting the number of elements can also be an expensive operation e.g. when using linked lists.

Co-Authored-By: Christoph Weitkamp <github@christophweitkamp.de>
Signed-off-by: Wouter Born <github@maindrain.net>
This commit is contained in:
Wouter Born 2019-10-21 09:00:52 +02:00 committed by Christoph Weitkamp
parent 55ddaa25fb
commit be69d2254e
35 changed files with 60 additions and 59 deletions

View File

@ -105,7 +105,7 @@ public class AudioConsoleCommandExtension extends AbstractConsoleCommandExtensio
private void listSources(Console console) {
Set<AudioSource> sources = audioManager.getAllSources();
if (sources.size() > 0) {
if (!sources.isEmpty()) {
AudioSource defaultSource = audioManager.getSource();
Locale locale = localeProvider.getLocale();
sources.stream().sorted(comparing(s -> s.getLabel(locale))).forEach(source -> {
@ -119,7 +119,7 @@ public class AudioConsoleCommandExtension extends AbstractConsoleCommandExtensio
private void listSinks(Console console) {
Set<AudioSink> sinks = audioManager.getAllSinks();
if (sinks.size() > 0) {
if (!sinks.isEmpty()) {
AudioSink defaultSink = audioManager.getSink();
Locale locale = localeProvider.getLocale();
sinks.stream().sorted(comparing(s -> s.getLabel(locale))).forEach(sink -> {

View File

@ -43,7 +43,7 @@ public class ItemRegistryDelegate implements Map<String, State> {
@Override
public boolean isEmpty() {
return size() == 0;
return itemRegistry.getAll().isEmpty();
}
@Override

View File

@ -142,7 +142,7 @@ public class ScriptModuleTypeProvider implements ModuleTypeProvider {
mimeTypes.addAll(f.getMimeTypes());
String preferredMimeType = mimeTypes.get(0);
mimeTypes.removeIf(mimeType -> !mimeType.contains("application") || mimeType.contains("x-"));
if (mimeTypes.size() > 0) {
if (!mimeTypes.isEmpty()) {
preferredMimeType = mimeTypes.get(0);
}
parameterOptions.add(new ParameterOption(preferredMimeType, languageName));

View File

@ -87,7 +87,7 @@ public class RulePredicates {
namespaceSet.add(namespace);
}
// this will even work for null namepace
// this will even work for null namespace
return r -> namespaceSet.contains(getPrefix(r));
}
@ -100,7 +100,7 @@ public class RulePredicates {
public static Predicate<Rule> hasTags() {
// everything with a tag is matching
// Rule.getTags() is never null
return r -> 0 < r.getTags().size();
return r -> !r.getTags().isEmpty();
}
/**

View File

@ -1348,7 +1348,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
Set<String> inputTags = input.getTags();
OutputRef outputRef = null;
boolean conflict = false;
if (inputTags.size() > 0) {
if (!inputTags.isEmpty()) {
for (Set<String> outTags : outputTagMap.keySet()) {
if (outTags.containsAll(inputTags)) { // input tags must be subset of the output ones
if (outputRef == null) {
@ -1371,7 +1371,7 @@ public class RuleEngineImpl implements RuleManager, RegistryChangeListener<Modul
private void initTagsMap(String moduleId, List<Output> outputs, Map<Set<String>, OutputRef> tagMap) {
for (Output output : outputs) {
Set<String> tags = output.getTags();
if (tags.size() > 0) {
if (!tags.isEmpty()) {
if (tagMap.get(tags) != null) {
// this set of output tags already exists. (conflict)
tagMap.remove(tags);

View File

@ -87,7 +87,7 @@ public class CompositeActionHandler extends AbstractCompositeModuleHandler<Actio
}
}
return result.size() > 0 ? result : null;
return !result.isEmpty() ? result : null;
}
/**

View File

@ -150,7 +150,7 @@ public class AnnotationActionModuleTypeHelper {
Set<ModuleInformation> mis = moduleInformation.get(UID);
List<ConfigDescriptionParameter> configDescriptions = new ArrayList<>();
if (mis != null && mis.size() > 0) {
if (mis != null && !mis.isEmpty()) {
ModuleInformation mi = (ModuleInformation) mis.toArray()[0];
ActionModuleKind kind = ActionModuleKind.SINGLE;

View File

@ -91,7 +91,7 @@ public abstract class AbstractActiveBinding<P extends BindingProvider> extends A
* @param properlyConfigured
*/
protected void setProperlyConfigured(boolean properlyConfigured) {
if (providers.size() > 0) {
if (!providers.isEmpty()) {
activeService.setProperlyConfigured(properlyConfigured);
}
}

View File

@ -56,7 +56,7 @@ public abstract interface GroupFunction {
*/
@Override
public State calculate(List<Item> items) {
if (items.size() > 0) {
if (!items.isEmpty()) {
State state = items.get(0).getState();
for (int i = 1; i < items.size(); i++) {
if (!state.equals(items.get(i).getState())) {

View File

@ -57,7 +57,7 @@ public interface ArithmeticGroupFunction extends GroupFunction {
*/
@Override
public State calculate(List<Item> items) {
if (items != null && items.size() > 0) {
if (items != null && !items.isEmpty()) {
for (Item item : items) {
if (!activeState.equals(item.getStateAs(activeState.getClass()))) {
return passiveState;
@ -325,7 +325,7 @@ public interface ArithmeticGroupFunction extends GroupFunction {
*/
@Override
public State calculate(List<Item> items) {
if (items != null && items.size() > 0) {
if (items != null && !items.isEmpty()) {
BigDecimal min = null;
for (Item item : items) {
DecimalType itemState = (DecimalType) item.getStateAs(DecimalType.class);
@ -372,7 +372,7 @@ public interface ArithmeticGroupFunction extends GroupFunction {
*/
@Override
public State calculate(List<Item> items) {
if (items != null && items.size() > 0) {
if (items != null && !items.isEmpty()) {
BigDecimal max = null;
for (Item item : items) {
DecimalType itemState = (DecimalType) item.getStateAs(DecimalType.class);

View File

@ -41,7 +41,7 @@ public class TransformationHelper {
try {
Collection<ServiceReference<org.eclipse.smarthome.core.transform.TransformationService>> refs = context
.getServiceReferences(org.eclipse.smarthome.core.transform.TransformationService.class, filter);
if (refs != null && refs.size() > 0) {
if (refs != null && !refs.isEmpty()) {
return new TransformationServiceDelegate(context.getService(refs.iterator().next()));
} else {
LOGGER.warn("Cannot get service reference for transformation service of type {}",

View File

@ -37,10 +37,10 @@ public class ConfigurationSerializer implements JsonSerializer<Configuration> {
public JsonElement serialize(Configuration src, Type typeOfSrc, JsonSerializationContext context) {
JsonObject result = null;
if (src != null) {
Set<String> kyes = src.keySet();
if (kyes.size() > 0) {
Set<String> keys = src.keySet();
if (!keys.isEmpty()) {
result = new JsonObject();
for (String propName : kyes) {
for (String propName : keys) {
Object value = src.get(propName);
if (value instanceof List) {
JsonArray array = new JsonArray();

View File

@ -120,7 +120,7 @@ public class ConverterAttributeMapValidator {
}
// there are still attributes in the validation mask left -> check if they are required
if ((validationMask != null) && (validationMask.size() > 0)) {
if (validationMask != null && !validationMask.isEmpty()) {
for (Map.Entry<String, Boolean> entry : validationMask.entrySet()) {
String attributeName = entry.getKey();
boolean attributeRequired = entry.getValue();

View File

@ -88,7 +88,7 @@ public class InstanceUUID {
} catch (IOException ioe) {
LOGGER.warn("Failed reading the UUID file '{}': {}", file.getAbsolutePath(), ioe.getMessage());
}
return lines != null && lines.size() > 0 ? lines.get(0) : "";
return lines == null || lines.isEmpty() ? "" : lines.get(0);
}
}

View File

@ -155,7 +155,7 @@ public class ItemConsoleCommandExtension extends AbstractConsoleCommandExtension
private void listItems(Console console, String pattern) {
Collection<Item> items = itemRegistry.getItems(pattern);
if (items.size() > 0) {
if (!items.isEmpty()) {
for (Item item : items) {
console.println(item.toString());
}

View File

@ -86,7 +86,7 @@ public class LogHandler implements RESTResource {
+ LogConstants.LOG_BUFFER_LIMIT + " last entries.")
@ApiParam(name = "limit", allowableValues = "range[1, " + LogConstants.LOG_BUFFER_LIMIT + "]")
public Response getLastLogs(@DefaultValue(LogConstants.LOG_BUFFER_LIMIT + "") @QueryParam("limit") Integer limit) {
if (logBuffer.size() <= 0) {
if (logBuffer.isEmpty()) {
return Response.ok("[]").build();
}

View File

@ -521,7 +521,7 @@ public class SitemapResource implements RESTResource, SitemapSubscriptionCallbac
bean.widgets.add(subWidget);
}
}
} else if (children.size() > 0) {
} else if (!children.isEmpty()) {
String pageName = itemUIRegistry.getWidgetId(linkableWidget);
bean.linkedPage = createPageBean(sitemapName, itemUIRegistry.getLabel(widget),
itemUIRegistry.getCategory(widget), pageName, drillDown ? children : null, drillDown,
@ -622,7 +622,7 @@ public class SitemapResource implements RESTResource, SitemapSubscriptionCallbac
}
} else if (w instanceof LinkableWidget) {
LinkableWidget linkableWidget = (LinkableWidget) w;
if (itemUIRegistry.getChildren(linkableWidget).size() > 0) {
if (!itemUIRegistry.getChildren(linkableWidget).isEmpty()) {
return false;
}
}

View File

@ -50,7 +50,7 @@ public class MDNSServiceImpl implements MDNSService {
protected void setMDNSClient(MDNSClient client) {
this.mdnsClient = client;
// register queued services
if (servicesToRegisterQueue.size() > 0) {
if (!servicesToRegisterQueue.isEmpty()) {
Runnable runnable = new Runnable() {
@Override
public void run() {

View File

@ -458,10 +458,10 @@ public class FeatureInstaller implements ConfigurationListener {
}
}
if (installed.size() > 0) {
if (!installed.isEmpty()) {
logger.debug("Installed '{}'", StringUtils.join(installed, ", "));
}
if (failed.size() > 0) {
if (!failed.isEmpty()) {
logger.error("Failed installing '{}'", StringUtils.join(failed, ", "));
}

View File

@ -79,7 +79,7 @@ public class ModelRepositoryImpl implements ModelRepository {
synchronized (resourceSet) {
Resource resource = getResource(name);
if (resource != null) {
if (resource.getContents().size() > 0) {
if (!resource.getContents().isEmpty()) {
return resource.getContents().get(0);
} else {
logger.warn("Configuration model '{}' is either empty or cannot be parsed correctly!", name);
@ -291,7 +291,7 @@ public class ModelRepositoryImpl implements ModelRepository {
for (org.eclipse.emf.common.util.Diagnostic d : diagnostic.getChildren()) {
warnings.add(d.getMessage());
}
if (warnings.size() > 0) {
if (!warnings.isEmpty()) {
logger.info("Validation issues found in configuration model '{}', using it anyway:\n{}", name,
StringUtils.join(warnings, "\n"));
}

View File

@ -135,7 +135,7 @@ public class ScriptEngineImpl implements ScriptEngine, ModelParser {
}
List<Diagnostic> errors = resource.getErrors();
if (errors.size() != 0) {
if (!errors.isEmpty()) {
throw new ScriptParsingException("Failed to parse expression (due to managed SyntaxError/s)",
scriptAsString).addDiagnosticErrors(errors);
}

View File

@ -222,7 +222,7 @@ public class JsonStorage<T> implements Storage<T> {
FileReader reader = new FileReader(inputFile);
Map<String, StorageEntry> loadedMap = internalMapper.fromJson(reader, map.getClass());
if (loadedMap != null && loadedMap.size() != 0) {
if (loadedMap != null && !loadedMap.isEmpty()) {
inputMap.putAll(loadedMap);
}

View File

@ -59,7 +59,7 @@ public class ChannelGroupTypeXmlResult {
throws ConversionException {
List<ChannelDefinition> channelTypeDefinitions = null;
if ((channelTypeReferences != null) && (channelTypeReferences.size() > 0)) {
if (channelTypeReferences != null && !channelTypeReferences.isEmpty()) {
channelTypeDefinitions = new ArrayList<>(channelTypeReferences.size());
for (ChannelXmlResult channelTypeReference : channelTypeReferences) {

View File

@ -91,7 +91,7 @@ public class ThingTypeXmlResult {
throws ConversionException {
List<ChannelDefinition> channelTypeDefinitions = null;
if ((channelTypeReferences != null) && (channelTypeReferences.size() > 0)) {
if (channelTypeReferences != null && !channelTypeReferences.isEmpty()) {
channelTypeDefinitions = new ArrayList<>(channelTypeReferences.size());
for (ChannelXmlResult channelTypeReference : channelTypeReferences) {
@ -106,7 +106,7 @@ public class ThingTypeXmlResult {
throws ConversionException {
List<ChannelGroupDefinition> channelGroupTypeDefinitions = null;
if ((channelGroupTypeReferences != null) && (channelGroupTypeReferences.size() > 0)) {
if (channelGroupTypeReferences != null && !channelGroupTypeReferences.isEmpty()) {
channelGroupTypeDefinitions = new ArrayList<>(channelGroupTypeReferences.size());
for (ChannelXmlResult channelGroupTypeReference : channelGroupTypeReferences) {
@ -120,7 +120,6 @@ public class ThingTypeXmlResult {
channelGroupTypeReference.getDescription());
channelGroupTypeDefinitions.add(channelGroupDefinition);
}
}

View File

@ -171,7 +171,7 @@ public abstract class BaseThingHandlerFactory implements ThingHandlerFactory {
}
}
}
if (serviceNames.size() > 0) {
if (!serviceNames.isEmpty()) {
String[] serviceNamesArray = serviceNames.toArray(new String[serviceNames.size()]);
ServiceRegistration<?> serviceReg = this.bundleContext.registerService(serviceNamesArray,

View File

@ -13,6 +13,7 @@
package org.eclipse.smarthome.core.thing.link;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ScheduledExecutorService;
import org.eclipse.jdt.annotation.NonNullByDefault;
@ -258,7 +259,7 @@ public class ThingLinkManager extends AbstractTypedEventSubscriber<ThingStatusIn
private void informHandlerAboutLinkedChannel(Thing thing, Channel channel) {
scheduler.submit(() -> {
// Don't notify the thing if the thing isn't initialised
// Don't notify the thing if the thing isn't initialized
if (ThingHandlerHelper.isHandlerInitialized(thing)) {
ThingHandler handler = thing.getHandler();
if (handler != null) {
@ -278,7 +279,7 @@ public class ThingLinkManager extends AbstractTypedEventSubscriber<ThingStatusIn
private void informHandlerAboutUnlinkedChannel(Thing thing, Channel channel) {
scheduler.submit(() -> {
// Don't notify the thing if the thing isn't initialised
// Don't notify the thing if the thing isn't initialized
if (ThingHandlerHelper.isHandlerInitialized(thing)) {
ThingHandler handler = thing.getHandler();
if (handler != null) {
@ -305,7 +306,8 @@ public class ThingLinkManager extends AbstractTypedEventSubscriber<ThingStatusIn
Thing thing = thingRegistry.get(event.getThingUID());
if (thing != null) {
for (Channel channel : thing.getChannels()) {
if (itemChannelLinkRegistry.getLinkedItemNames(channel.getUID()).size() > 0) {
Set<String> linkedItemNames = itemChannelLinkRegistry.getLinkedItemNames(channel.getUID());
if (!linkedItemNames.isEmpty()) {
informHandlerAboutLinkedChannel(thing, channel);
}
}

View File

@ -65,7 +65,7 @@ public class TransformationHelper {
try {
Collection<ServiceReference<TransformationService>> refs = context
.getServiceReferences(TransformationService.class, filter);
if (refs != null && refs.size() > 0) {
if (refs != null && !refs.isEmpty()) {
return context.getService(refs.iterator().next());
} else {
LOGGER.debug("Cannot get service reference for transformation service of type {}",
@ -116,7 +116,7 @@ public class TransformationHelper {
* @param state the state to be formatted before being passed into the transformation function
* @return the result of the transformation. If no transformation was done, <code>null</code> is returned
* @throws TransformationException if transformation service fails or the state cannot be formatted according to the
* format
* format
*/
public static @Nullable String transform(TransformationService service, String function, String format,
String state) throws TransformationException {

View File

@ -751,9 +751,9 @@ public abstract class AbstractRuleBasedInterpreter implements HumanLanguageInter
Set<String> remainder = new HashSet<>(identifierExcludes);
Expression stopper = expression.getStopper();
Set<String> excludes = stopper == null ? new HashSet<>() : stopper.getFirsts(language);
if (excludes.size() > 0) {
if (!excludes.isEmpty()) {
remainder.removeAll(excludes);
if (remainder.size() > 0) {
if (!remainder.isEmpty()) {
emit("(");
}
emit("<idbase>");
@ -761,7 +761,7 @@ public abstract class AbstractRuleBasedInterpreter implements HumanLanguageInter
emit(" | ");
emit(token);
}
if (remainder.size() > 0) {
if (!remainder.isEmpty()) {
emit(")");
}
} else {
@ -815,7 +815,7 @@ public abstract class AbstractRuleBasedInterpreter implements HumanLanguageInter
emit("#JSGF V1.0;\n\n");
if (identifierExcludes.size() > 0) {
if (!identifierExcludes.isEmpty()) {
Set<String> identifierBase = new HashSet<>(identifiers);
identifierBase.removeAll(identifierExcludes);
emit("<idbase> = ");

View File

@ -62,7 +62,7 @@ public final class ExpressionCardinality extends Expression {
node.setChildren(nodes.toArray(new ASTNode[0]));
node.setRemainingTokens(list);
node.setSuccess(true);
node.setValue(atMostOne ? (values.size() > 0 ? values.get(0) : null) : values.toArray());
node.setValue(atMostOne ? (values.isEmpty() ? null : values.get(0)) : values.toArray());
generateValue(node);
}
return node;

View File

@ -95,7 +95,7 @@ public class LanguageResourceBundleManager {
* @return true if the according bundle provides resource information, otherwise false
*/
public boolean containsResources() {
return (this.resourceNames.size() > 0);
return !resourceNames.isEmpty();
}
private List<String> determineResourceNames() {

View File

@ -61,7 +61,7 @@ public interface GroupFunction {
@Override
public State calculate(Set<Item> items) {
if (items.size() > 0) {
if (!items.isEmpty()) {
Iterator<Item> it = items.iterator();
State state = it.next().getState();
while (it.hasNext()) {

View File

@ -155,7 +155,7 @@ public class ManagedItemProvider extends AbstractManagedProvider<Item, String, P
protected void addItemFactory(ItemFactory itemFactory) {
itemFactories.add(itemFactory);
if (failedToCreate.size() > 0) {
if (!failedToCreate.isEmpty()) {
// retry failed creation attempts
Iterator<Entry<String, PersistedItem>> iterator = failedToCreate.entrySet().iterator();
while (iterator.hasNext()) {

View File

@ -55,7 +55,7 @@ public interface ArithmeticGroupFunction extends GroupFunction {
@Override
public State calculate(Set<Item> items) {
if (items != null && items.size() > 0) {
if (items != null && !items.isEmpty()) {
for (Item item : items) {
if (!activeState.equals(item.getStateAs(activeState.getClass()))) {
return passiveState;
@ -303,7 +303,7 @@ public interface ArithmeticGroupFunction extends GroupFunction {
@Override
public State calculate(Set<Item> items) {
if (items != null && items.size() > 0) {
if (items != null && !items.isEmpty()) {
BigDecimal min = null;
for (Item item : items) {
DecimalType itemState = item.getStateAs(DecimalType.class);
@ -346,7 +346,7 @@ public interface ArithmeticGroupFunction extends GroupFunction {
@Override
public State calculate(Set<Item> items) {
if (items != null && items.size() > 0) {
if (items != null && !items.isEmpty()) {
BigDecimal max = null;
for (Item item : items) {
DecimalType itemState = item.getStateAs(DecimalType.class);

View File

@ -37,7 +37,7 @@ public interface DateTimeGroupFunction extends GroupFunction {
@Override
public State calculate(Set<Item> items) {
if (items != null && items.size() > 0) {
if (items != null && !items.isEmpty()) {
ZonedDateTime max = null;
for (Item item : items) {
DateTimeType itemState = item.getStateAs(DateTimeType.class);
@ -80,7 +80,7 @@ public interface DateTimeGroupFunction extends GroupFunction {
@Override
public State calculate(Set<Item> items) {
if (items != null && items.size() > 0) {
if (items != null && !items.isEmpty()) {
ZonedDateTime max = null;
for (Item item : items) {
DateTimeType itemState = item.getStateAs(DateTimeType.class);

View File

@ -77,7 +77,7 @@ public interface QuantityTypeArithmeticGroupFunction extends GroupFunction {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public State calculate(Set<Item> items) {
if (items == null || items.size() <= 0) {
if (items == null || items.isEmpty()) {
return UnDefType.UNDEF;
}
@ -120,7 +120,7 @@ public interface QuantityTypeArithmeticGroupFunction extends GroupFunction {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public State calculate(Set<Item> items) {
if (items == null || items.size() <= 0) {
if (items == null || items.isEmpty()) {
return UnDefType.UNDEF;
}
@ -155,7 +155,7 @@ public interface QuantityTypeArithmeticGroupFunction extends GroupFunction {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public State calculate(Set<Item> items) {
if (items == null || items.size() <= 0) {
if (items == null || items.isEmpty()) {
return UnDefType.UNDEF;
}
@ -188,7 +188,7 @@ public interface QuantityTypeArithmeticGroupFunction extends GroupFunction {
@Override
@SuppressWarnings({ "unchecked", "rawtypes" })
public State calculate(Set<Item> items) {
if (items == null || items.size() <= 0) {
if (items == null || items.isEmpty()) {
return UnDefType.UNDEF;
}