简体   繁体   中英

Java 8 - How to create Iterable from List<T> and new T without creating temporary variable?

Is it possible to put Iterable<? extends Module> modules Iterable<? extends Module> modules without creating temporary variable ms and add new element?

List<Module> ms = new ArrayList<>(super.superModules);
ms.add(new newModule());
Injector injector = Guice.createInjector(super.stage, ms);

In parent:

protected List<Module> superModules= new ArrayList<>(Arrays.asList(CucumberModules.createScenarioModule(), new aaaModule(), new bbbModule(), new cccModule()));

My called method:

public static Injector createInjector(Stage stage, Iterable<? extends Module> modules) {
    return new InternalInjectorCreator().stage(stage).addModules(modules).build();
}

Having a mutable list called 'superModules' sounds like a bad idea; I don't think you'd want any other code to be able to modify this list, no?

Assuming you have java11+ , you can just write: protected final List<Module> superModules = List.of(CucumberModules.createScenarioModule(), ...);

Then, I understand you want to make a new list, containing all the elements from this list + one more element. No, there is no simple one-liner to mix up a list and an element.

There are hacks which I strongly advise you don't use. For example:

Stream.of(super.superModules, List.of(new NewModule()).flatMap(List::stream).collect(Collectors.toList());

these just serve to obfuscate what you're trying to do. I wouldn't even put the above on a single line for readability purposes.

Java 8:

Injector injector = Guice.createInjector(super.stage, () ->
                    Stream.concat(super.superModules.stream(), Stream.of(new NewModule()))
                    .iterator());

Since the createInjector method does not require a List , you don't need to construct a List . You can use

Injector injector = Guice.createInjector(super.stage, () ->
    Stream.concat(super.superModules.stream(), Stream.of(new NewModule())).iterator());

The Iterable is a functional interface, as its only abstract method is iterator() , which can be fulfilled by a function providing an Iterator on demand.

There are 3rd party libraries offering Iterator composition, so you could combine super.superModules.iterator() with new NewModule() as another element. With builtin facilities, we can construct a concatenated stream and convert it to an iterator. This still avoids allocating new storage for a composed collection.

你可以做 Arrays.asList(module1, module2, module3)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM