Skip to content

Commit

Permalink
Simplify code using Stream.toList (openhab#3831)
Browse files Browse the repository at this point in the history
Stream.toList was introduced in Java 16 and creates an unmodifiable List so it can be used to simplify code whenever the List is not expected to be modified.

Signed-off-by: Wouter Born <[email protected]>
  • Loading branch information
wborn authored Oct 9, 2023
1 parent 2794c97 commit 09b3160
Show file tree
Hide file tree
Showing 93 changed files with 293 additions and 470 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import java.nio.file.StandardCopyOption;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.karaf.kar.KarService;
Expand Down Expand Up @@ -123,7 +122,7 @@ public void uninstall(Addon addon) throws MarketplaceHandlerException {
try {
Path addonPath = getAddonCacheDirectory(addon.getUid());
List<String> repositories = karService.list();
for (Path path : karFilesStream(addonPath).collect(Collectors.toList())) {
for (Path path : karFilesStream(addonPath).toList()) {
String karRepoName = pathToKarRepoName(path);
if (repositories.contains(karRepoName)) {
karService.uninstall(karRepoName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,6 @@
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -117,7 +116,7 @@ public void refreshSource() {
}

// create lookup list to make sure installed addons take precedence
List<String> installedAddons = addons.stream().map(Addon::getUid).collect(Collectors.toList());
List<String> installedAddons = addons.stream().map(Addon::getUid).toList();

if (remoteEnabled()) {
List<Addon> remoteAddons = Objects.requireNonNullElse(cachedRemoteAddons.getValue(), List.of());
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -188,7 +187,7 @@ protected List<Addon> getRemoteAddons() {
}
}

List<DiscourseUser> users = pages.stream().flatMap(p -> Stream.of(p.users)).collect(Collectors.toList());
List<DiscourseUser> users = pages.stream().flatMap(p -> Stream.of(p.users)).toList();
pages.stream().flatMap(p -> Stream.of(p.topicList.topics))
.filter(t -> showUnpublished || Arrays.asList(t.tags).contains(PUBLISHED_TAG))
.map(t -> Optional.ofNullable(convertTopicItemToAddon(t, users)))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -46,7 +45,7 @@ public PropertyName findNameForDeserialization(Annotated annotated) {
@NonNullByDefault({})
public List<PropertyName> findPropertyAliases(Annotated annotated) {
return Optional.ofNullable(annotated.getAnnotation(SerializedName.class))
.map(s -> Stream.of(s.alternate()).map(PropertyName::new).collect(Collectors.toList()))
.map(s -> Stream.of(s.alternate()).map(PropertyName::new).toList())
.orElseGet(() -> super.findPropertyAliases(annotated));
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -133,8 +132,7 @@ protected List<Addon> getRemoteAddons() {
return List.of();
}
}).flatMap(List::stream).filter(Objects::nonNull).map(e -> (AddonEntryDTO) e)
.filter(e -> showUnstable || "stable".equals(e.maturity)).map(this::fromAddonEntry)
.collect(Collectors.toList());
.filter(e -> showUnstable || "stable".equals(e.maturity)).map(this::fromAddonEntry).toList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -76,7 +75,7 @@ protected List<Addon> getRemoteAddons() {
remoteCalls++;
return REMOTE_ADDONS.stream().map(id -> Addon.create(SERVICE_PID + ":" + id).withType("binding")
.withId(id.substring("binding-".length())).withContentType(TestAddonHandler.TEST_ADDON_CONTENT_TYPE)
.withCompatible(!id.equals(INCOMPATIBLE_VERSION)).build()).collect(Collectors.toList());
.withCompatible(!id.equals(INCOMPATIBLE_VERSION)).build()).toList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
package org.openhab.core.audio.internal;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

import java.io.File;
import java.io.IOException;
Expand Down Expand Up @@ -312,10 +311,10 @@ public Set<String> getSinkIds(String pattern) {
final Locale safeLocale = locale != null ? locale : Locale.getDefault();
if (CONFIG_DEFAULT_SOURCE.equals(param)) {
return audioSources.values().stream().sorted(comparing(s -> s.getLabel(safeLocale)))
.map(s -> new ParameterOption(s.getId(), s.getLabel(safeLocale))).collect(toList());
.map(s -> new ParameterOption(s.getId(), s.getLabel(safeLocale))).toList();
} else if (CONFIG_DEFAULT_SINK.equals(param)) {
return audioSinks.values().stream().sorted(comparing(s -> s.getLabel(safeLocale)))
.map(s -> new ParameterOption(s.getId(), s.getLabel(safeLocale))).collect(toList());
.map(s -> new ParameterOption(s.getId(), s.getLabel(safeLocale))).toList();
}
}
return null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.servlet.Servlet;
Expand Down Expand Up @@ -172,7 +171,7 @@ protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws Se
final String streamId = substringBefore(substringAfterLast(requestURI, "/"), ".");

List<String> acceptedMimeTypes = Stream.of(Objects.requireNonNullElse(req.getHeader("Accept"), "").split(","))
.map(String::trim).collect(Collectors.toList());
.map(String::trim).toList();

StreamServed servedStream = servedStreams.get(streamId);
if (servedStream == null) {
Expand Down Expand Up @@ -219,7 +218,7 @@ private synchronized void removeTimedOutStreams() {
long now = System.nanoTime();
final List<String> toRemove = servedStreams.entrySet().stream()
.filter(e -> e.getValue().timeout().get() < now && e.getValue().currentlyServedStream().get() <= 0)
.map(Entry::getKey).collect(Collectors.toList());
.map(Entry::getKey).toList();

toRemove.forEach(streamId -> {
// the stream has expired and no one is using it, we need to remove it!
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
package org.openhab.core.automation.module.media.internal;

import static java.util.Comparator.comparing;
import static java.util.stream.Collectors.toList;

import java.io.File;
import java.math.BigDecimal;
Expand Down Expand Up @@ -162,7 +161,7 @@ private List<ParameterOption> getSoundOptions() {
private List<ParameterOption> getSinkOptions(@Nullable Locale locale) {
final Locale safeLocale = locale != null ? locale : Locale.getDefault();
return audioManager.getAllSinks().stream().sorted(comparing(s -> s.getLabel(safeLocale)))
.map(s -> new ParameterOption(s.getId(), s.getLabel(safeLocale))).collect(toList());
.map(s -> new ParameterOption(s.getId(), s.getLabel(safeLocale))).toList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@
import java.util.concurrent.locks.ReentrantLock;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import javax.script.Compilable;
import javax.script.CompiledScript;
Expand Down Expand Up @@ -246,7 +245,7 @@ public void updated(Transformation oldElement, Transformation element) {

if (ScriptProfile.CONFIG_TO_HANDLER_SCRIPT.equals(param) || ScriptProfile.CONFIG_TO_ITEM_SCRIPT.equals(param)) {
return transformationRegistry.getTransformations(List.of(scriptType.toLowerCase())).stream()
.map(c -> new ParameterOption(c.getUID(), c.getLabel())).collect(Collectors.toList());
.map(c -> new ParameterOption(c.getUID(), c.getLabel())).toList();
}
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import java.util.List;
import java.util.Map;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import javax.annotation.security.RolesAllowed;
Expand Down Expand Up @@ -433,7 +432,7 @@ public Response simulateRules(
}

final Stream<RuleExecution> ruleExecutions = ruleManager.simulateRuleExecutions(fromDate, untilDate);
return Response.ok(ruleExecutions.collect(Collectors.toList())).build();
return Response.ok(ruleExecutions.toList()).build();
}

private static ZonedDateTime parseTime(String sTime) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

import java.util.Collection;
import java.util.Locale;
import java.util.stream.Collectors;

import javax.ws.rs.GET;
import javax.ws.rs.HeaderParam;
Expand Down Expand Up @@ -92,7 +91,7 @@ public Response getAll(
@HeaderParam("Accept-Language") @Parameter(description = "language") @Nullable String language) {
Locale locale = localeService.getLocale(language);
Collection<RuleTemplateDTO> result = templateRegistry.getAll(locale).stream()
.map(template -> RuleTemplateDTOMapper.map(template)).collect(Collectors.toList());
.map(template -> RuleTemplateDTOMapper.map(template)).toList();
return Response.ok(result).build();
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -388,7 +387,7 @@ protected List<ConfigDescriptionParameter> getLocalizedConfigurationDescription(
URI uri = new URI(prefix + ":" + uid + ".name");
return config.stream()
.map(p -> localConfigI18nService.getLocalizedConfigDescriptionParameter(bundle, uri, p, locale))
.collect(Collectors.toList());
.toList();
} catch (URISyntaxException e) {
logger.error("Constructed invalid uri '{}:{}.name'", prefix, uid, e);
return config;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
import java.util.LinkedList;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.core.automation.Module;
Expand All @@ -37,12 +36,11 @@ public class WrappedRule {

private static <T extends WrappedModule, U extends Module> List<T> map(final List<U> in, Function<U, T> factory,
final Collection<WrappedModule<Module, ModuleHandler>> coll) {
// explicit cast to List <? extends T> as JDK compiler complains
return Collections.unmodifiableList((List<? extends T>) in.stream().map(module -> {
return in.stream().map(module -> {
final T impl = factory.apply(module);
coll.add(impl);
return impl;
}).collect(Collectors.toList()));
}).toList();
}

private final Rule rule;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,15 +17,14 @@
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.jdt.annotation.NonNull;
import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -118,14 +117,13 @@ public static void applyDefaultConfiguration(Configuration configuration,
if (defaultValue != null && configuration.get(parameter.getName()) == null) {
if (parameter.isMultiple()) {
if (defaultValue.contains(DEFAULT_LIST_DELIMITER)) {
List<Object> values = (List<Object>) List.of(defaultValue.split(DEFAULT_LIST_DELIMITER))
.stream() //
List<Object> values = (List<Object>) Stream.of(defaultValue.split(DEFAULT_LIST_DELIMITER))
.map(String::trim) //
.filter(not(String::isEmpty)) //
.map(value -> ConfigUtil.getDefaultValueAsCorrectType(parameter.getName(),
parameter.getType(), value)) //
.filter(Objects::nonNull) //
.collect(Collectors.toList());
.toList();
Integer multipleLimit = parameter.getMultipleLimit();
if (multipleLimit != null && values.size() > multipleLimit.intValue()) {
LoggerFactory.getLogger(ConfigUtil.class).warn(
Expand All @@ -136,7 +134,7 @@ public static void applyDefaultConfiguration(Configuration configuration,
} else {
Object value = ConfigUtil.getDefaultValueAsCorrectType(parameter);
if (value != null) {
configuration.put(parameter.getName(), Arrays.asList(value));
configuration.put(parameter.getName(), List.of(value));
}
}
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -82,7 +81,7 @@ private Collection<ParameterOption> processTimeZoneParam() {
Comparator<TimeZone> byOffset = (t1, t2) -> t1.getRawOffset() - t2.getRawOffset();
Comparator<TimeZone> byID = (t1, t2) -> t1.getID().compareTo(t2.getID());
return ZoneId.getAvailableZoneIds().stream().map(TimeZone::getTimeZone).sorted(byOffset.thenComparing(byID))
.map(tz -> new ParameterOption(tz.getID(), getTimeZoneRepresentation(tz))).collect(Collectors.toList());
.map(tz -> new ParameterOption(tz.getID(), getTimeZoneRepresentation(tz))).toList();
}

private static String getTimeZoneRepresentation(TimeZone tz) {
Expand All @@ -107,6 +106,6 @@ private Collection<ParameterOption> getAvailable(@Nullable Locale locale,
.distinct() //
.filter(po -> !po.getValue().isEmpty()) //
.sorted(Comparator.comparing(a -> a.getLabel())) //
.collect(Collectors.toList());
.toList();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.util.Collection;
import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.eclipse.jdt.annotation.NonNullByDefault;
Expand Down Expand Up @@ -52,13 +51,11 @@ public class NetworkConfigOptionProvider implements ConfigOptionProvider {
case PARAM_PRIMARY_ADDRESS:
Stream<CidrAddress> ipv4Addresses = NetUtil.getAllInterfaceAddresses().stream()
.filter(a -> a.getAddress() instanceof Inet4Address);
return ipv4Addresses.map(a -> new ParameterOption(a.toString(), a.toString()))
.collect(Collectors.toList());
return ipv4Addresses.map(a -> new ParameterOption(a.toString(), a.toString())).toList();
case PARAM_BROADCAST_ADDRESS:
List<String> broadcastAddrList = new ArrayList<>(NetUtil.getAllBroadcastAddresses());
broadcastAddrList.add("255.255.255.255");
return broadcastAddrList.stream().distinct().map(a -> new ParameterOption(a, a))
.collect(Collectors.toList());
return broadcastAddrList.stream().distinct().map(a -> new ParameterOption(a, a)).toList();
default:
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@
import java.util.Collections;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.eclipse.jdt.annotation.Nullable;
Expand Down Expand Up @@ -137,7 +136,7 @@ private Collection<ConfigStatusMessage> filter(Collection<?> filter, Predicate<C

private static Collection<ConfigStatusMessage> filterConfigStatusMessages(
Collection<ConfigStatusMessage> configStatusMessages, Predicate<? super ConfigStatusMessage> predicate) {
return configStatusMessages.stream().filter(predicate).collect(Collectors.toList());
return configStatusMessages.stream().filter(predicate).toList();
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
*/
package org.openhab.core.config.core.internal.normalization;

import static java.util.stream.Collectors.toList;
import static org.hamcrest.CoreMatchers.*;
import static org.hamcrest.MatcherAssert.assertThat;

Expand Down Expand Up @@ -153,14 +152,13 @@ public void testListNormalizer() {

assertThat(normalizer.normalize(null), is(nullValue()));

List<Boolean> expectedList = Stream.of(true, false, true).collect(toList());
List<Boolean> expectedList = Stream.of(true, false, true).toList();

assertThat(normalizer.normalize(Stream.of(true, false, true).collect(toList())), is(equalTo(expectedList)));
assertThat(normalizer.normalize(Stream.of(true, false, true).collect(toList()).toArray()),
is(equalTo(expectedList)));
assertThat(normalizer.normalize(new TreeSet<>(Stream.of(false, true).collect(toList()))),
is(equalTo(Stream.of(false, true).collect(toList()))));
assertThat(normalizer.normalize(Stream.of(true, "false", true).collect(toList())), is(equalTo(expectedList)));
assertThat(normalizer.normalize(Stream.of(true, 0, "true").collect(toList())), is(equalTo(expectedList)));
assertThat(normalizer.normalize(Stream.of(true, false, true).toList()), is(equalTo(expectedList)));
assertThat(normalizer.normalize(Stream.of(true, false, true).toArray()), is(equalTo(expectedList)));
assertThat(normalizer.normalize(new TreeSet<>(Stream.of(false, true).toList())),
is(equalTo(Stream.of(false, true).toList())));
assertThat(normalizer.normalize(Stream.of(true, "false", true).toList()), is(equalTo(expectedList)));
assertThat(normalizer.normalize(Stream.of(true, 0, "true").toList()), is(equalTo(expectedList)));
}
}
Loading

0 comments on commit 09b3160

Please sign in to comment.