01 /*
02 * Java Genetic Algorithm Library (jenetics-5.1.0).
03 * Copyright (c) 2007-2019 Franz Wilhelmstötter
04 *
05 * Licensed under the Apache License, Version 2.0 (the "License");
06 * you may not use this file except in compliance with the License.
07 * You may obtain a copy of the License at
08 *
09 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 * Author:
18 * Franz Wilhelmstötter (franz.wilhelmstoetter@gmail.com)
19 */
20 package io.jenetics.ext.internal;
21
22 import java.util.ArrayList;
23 import java.util.List;
24 import java.util.Objects;
25 import java.util.Spliterator;
26 import java.util.function.Consumer;
27 import java.util.function.Supplier;
28 import java.util.stream.Collectors;
29
30 /**
31 * @author <a href="mailto:franz.wilhelmstoetter@gmail.com">Franz Wilhelmstötter</a>
32 * @version 4.1
33 * @since 4.1
34 */
35 public class CyclicSpliterator<T> implements Spliterator<T> {
36
37 private final List<Supplier<Spliterator<T>>> _spliterators;
38
39 private ConcatSpliterator<T> _concat = null;
40
41 public CyclicSpliterator(final List<Supplier<Spliterator<T>>> spliterators) {
42 spliterators.forEach(Objects::requireNonNull);
43 _spliterators = new ArrayList<>(spliterators);
44 }
45
46 @Override
47 public boolean tryAdvance(final Consumer<? super T> action) {
48 boolean advance = true;
49 if (_spliterators.isEmpty()) {
50 advance = false;
51 } else {
52 if (!spliterator().tryAdvance(action)) {
53 _concat = null;
54 }
55 }
56
57 return advance;
58 }
59
60 @Override
61 public Spliterator<T> trySplit() {
62 return new CyclicSpliterator<>(_spliterators);
63 }
64
65 @Override
66 public long estimateSize() {
67 return Long.MAX_VALUE;
68 }
69
70 @Override
71 public int characteristics() {
72 return Spliterator.ORDERED;
73 }
74
75 private ConcatSpliterator<T> spliterator() {
76 if (_concat == null) {
77 _concat = new ConcatSpliterator<T>(
78 _spliterators.stream()
79 .map(Supplier::get)
80 .collect(Collectors.toList())
81 );
82 }
83
84 return _concat;
85 }
86
87 }
|