summaryrefslogtreecommitdiff
path: root/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java
blob: 72c5843ddc8c908f410a9eaf22c0bb03eacd4760 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463

package bjc.utils.funcdata;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

import bjc.utils.data.GenHolder;
import bjc.utils.data.IHolder;
import bjc.utils.data.Pair;

/**
 * A wrapper over another list that provides eager functional operations
 * over it. Differs from a stream in every way except for the fact that
 * they both provide functional operations.
 * 
 * @author ben
 *
 * @param <E>
 *            The type in this list
 */
public class FunctionalList<E> implements Cloneable {
	/**
	 * The list used as a backing store
	 */
	private List<E> wrap;

	/**
	 * Create a new empty functional list.
	 */
	public FunctionalList() {
		wrap = new ArrayList<>();
	}

	/**
	 * Create a new functional list containing the specified items.
	 * 
	 * @param items
	 *            The items to put into this functional list.
	 */
	@SafeVarargs
	public FunctionalList(E... items) {
		wrap = new ArrayList<>(items.length);

		for (E item : items) {
			wrap.add(item);
		}
	}

	/**
	 * Create a functional list using the same backing list as the provided
	 * list.
	 * 
	 * @param fl
	 *            The source for a backing list
	 */
	public FunctionalList(FunctionalList<E> fl) {
		// TODO Find out if this should make a copy of fl.wrap instead.
		wrap = fl.wrap;
	}

	/**
	 * Create a new functional list with the specified size.
	 * 
	 * @param sz
	 *            The size of the backing list .
	 */
	private FunctionalList(int sz) {
		wrap = new ArrayList<>(sz);
	}

	/**
	 * Create a new functional list as a wrapper of a existing list.
	 * 
	 * @param l
	 *            The list to use as a backing list.
	 */
	public FunctionalList(List<E> l) {
		wrap = l;
	}

	/**
	 * Add an item to this list
	 * 
	 * @param item
	 *            The item to add to this list.
	 * @return Whether the item was added to the list succesfully.
	 */
	public boolean add(E item) {
		return wrap.add(item);
	}

	/**
	 * Check if all of the elements of this list match the specified
	 * predicate.
	 * 
	 * @param p
	 *            The predicate to use for checking.
	 * @return Whether all of the elements of the list match the specified
	 *         predicate.
	 */
	public boolean allMatch(Predicate<E> p) {
		for (E item : wrap) {
			if (!p.test(item)) {
				return false;
			}
		}
		return true;
	}

	/**
	 * Check if any of the elements in this list match the specified list.
	 * 
	 * @param p
	 *            The predicate to use for checking.
	 * @return Whether any element in the list matches the provided
	 *         predicate.
	 */
	public boolean anyMatch(Predicate<E> p) {
		for (E item : wrap) {
			if (p.test(item)) {
				return true;
			}
		}

		return false;
	}

	@Override
	public FunctionalList<E> clone() {
		FunctionalList<E> fl = new FunctionalList<>();

		for (E ele : wrap) {
			fl.add(ele);
		}

		return fl;
	}

	/**
	 * Combine this list with another one into a new list and merge the
	 * results. Works sort of like a combined zip/map over resulting pairs.
	 * Does not change the underlying list.
	 * 
	 * NOTE: The returned list will have the length of the shorter of this
	 * list and the combined one.
	 * 
	 * @param l
	 *            The list to combine with
	 * @param bf
	 *            The function to use for combining element pairs.
	 * @return A new list containing the merged pairs of lists.
	 */
	public <T, F> FunctionalList<F> combineWith(FunctionalList<T> l,
			BiFunction<E, T, F> bf) {
		FunctionalList<F> r = new FunctionalList<>();

		Iterator<T> i2 = l.wrap.iterator();

		for (Iterator<E> i1 = wrap.iterator(); i1.hasNext()
				&& i2.hasNext();) {
			r.add(bf.apply(i1.next(), i2.next()));
		}

		return r;
	}

	/**
	 * Check if the list contains the specified item
	 * 
	 * @param item
	 *            The item to see if it is contained
	 * @return Whether or not the specified item is in the list
	 */
	public boolean contains(E item) {
		return this.anyMatch(item::equals);
	}

	/**
	 * Get the first element in the list
	 * 
	 * @return The first element in this list.
	 */
	public E first() {
		return wrap.get(0);
	}

	/**
	 * Apply a function to each member of the list, then flatten the
	 * results. Does not change the underlying list.
	 * 
	 * @param f
	 *            The function to apply to each member of the list.
	 * @return A new list containing the flattened results of applying the
	 *         provided function.
	 */
	public <T> FunctionalList<T> flatMap(Function<E, List<T>> f) {
		FunctionalList<T> fl = new FunctionalList<>(this.wrap.size());

		forEach(e -> f.apply(e).forEach(fl::add));

		return fl;
	}

	/**
	 * Apply a given action for each member of the list
	 * 
	 * @param c
	 *            The action to apply to each member of the list.
	 */
	public void forEach(Consumer<E> c) {
		wrap.forEach(c);
	}

	/**
	 * Apply a given function to each element in the list and its index.
	 * 
	 * @param c
	 *            The function to apply to each element in the list and its
	 *            index.
	 */
	public void forEachIndexed(BiConsumer<Integer, E> c) {
		GenHolder<Integer> i = new GenHolder<>(0);

		wrap.forEach((val) -> {
			c.accept(i.unwrap(vl -> vl), val);

			i.transform((vl) -> vl + 1);
		});
	}

	/**
	 * Retrieve a value in the list by its index.
	 * 
	 * @param i
	 *            The index to retrieve a value from.
	 * @return The value at the specified index in the list.
	 */
	public E getByIndex(int i) {
		return wrap.get(i);
	}

	/**
	 * Get the internal backing list.
	 * 
	 * @return The backing list this list is based off of.
	 */
	public List<E> getInternal() {
		return wrap;
	}

	/**
	 * Retrieve a list containing all elements matching a predicate
	 * 
	 * @param matchPred
	 *            The predicate to match by
	 * @return A list containing all elements that match the predicate
	 */
	public FunctionalList<E> getMatching(Predicate<E> matchPred) {
		FunctionalList<E> fl = new FunctionalList<>();

		wrap.forEach((elem) -> {
			if (matchPred.test(elem)) {
				fl.add(elem);
			}
		});

		return fl;
	}

	/**
	 * Check if this list is empty.
	 * 
	 * @return Whether or not this list is empty.
	 */
	public boolean isEmpty() {
		return wrap.isEmpty();
	}

	/**
	 * Create a new list by applying the given function to each element in
	 * the list. Does not change the underlying list.
	 * 
	 * @param f
	 *            The function to apply to each element in the list
	 * @return A new list containing the mapped elements of this list.
	 */
	public <T> FunctionalList<T> map(Function<E, T> f) {
		FunctionalList<T> fl = new FunctionalList<>(this.wrap.size());

		forEach(e -> fl.add(f.apply(e)));

		return fl;
	}

	/**
	 * Zip two lists into a list of pairs
	 * 
	 * @param fl
	 *            The list to use as the left side of the pair
	 * @return A list containing pairs of this element and the specified
	 *         list
	 */
	public <T> FunctionalList<Pair<E, T>> pairWith(FunctionalList<T> fl) {
		return combineWith(fl, Pair<E, T>::new);
	}

	/**
	 * Prepend an item to the list
	 * 
	 * @param item
	 *            The item to prepend to the list
	 */
	public void prepend(E item) {
		wrap.add(0, item);
	}

	/**
	 * Select a random item from this list, using the provided random
	 * number generator.
	 * 
	 * @param rnd
	 *            The random number generator to use.
	 * @return A random element from this list.
	 */
	public E randItem(Random rnd) {
		return wrap.get(rnd.nextInt(wrap.size()));
	}

	/**
	 * Reduce this list to a single value, using a accumulative approach.
	 * 
	 * @param val
	 *            The initial value of the accumulative state.
	 * @param bf
	 *            The function to use to combine a list element with the
	 *            accumulative state.
	 * @param finl
	 *            The function to use to convert the accumulative state
	 *            into a final result.
	 * @return A single value condensed from this list and transformed into
	 *         its final state.
	 */
	public <T, F> F reduceAux(T val, BiFunction<E, T, T> bf,
			Function<T, F> finl) {
		IHolder<T> acum = new GenHolder<>(val);

		wrap.forEach(e -> acum.transform((vl) -> bf.apply(e, vl)));

		return acum.unwrap(finl);
	}

	/**
	 * Remove all elements that match a given predicate
	 * 
	 * @param remPred
	 *            The predicate to use to determine elements to delete
	 * @return Whether there was anything that satisfied the predicate
	 */
	public boolean removeIf(Predicate<E> remPred) {
		return wrap.removeIf(remPred);
	}

	public void removeMatching(E obj) {
		removeIf((ele) -> ele.equals(obj));
	}

	/**
	 * Perform a binary search for the specified key using the provided
	 * means of comparing elements. Since this IS a binary search, the list
	 * must have been sorted before hand.
	 * 
	 * @param key
	 *            The key to search for.
	 * @param cmp
	 *            The way to compare elements for searching
	 * @return The element if it is in this list, or null if it is not.
	 */
	public E search(E key, Comparator<E> cmp) {
		int res = Collections.binarySearch(wrap, key, cmp);

		return (res >= 0) ? wrap.get(res) : null;
	}

	/**
	 * Sort the elements of this list using the provided way of comparing
	 * elements. Does change the underlying list.
	 * 
	 * @param cmp
	 *            The way to compare elements for sorting.
	 */
	public void sort(Comparator<E> cmp) {
		Collections.sort(wrap, cmp);
	}

	/**
	 * Convert the list into a iterable
	 * 
	 * @return An iterable view onto the list
	 */
	public Iterable<E> toIterable() {
		return wrap;
	}

	/*
	 * Reduce this item to a form useful for looking at in the debugger.
	 * (non-Javadoc)
	 * 
	 * @see java.lang.Object#toString()
	 */
	public String toString() {
		StringBuilder sb = new StringBuilder("(");

		forEach(s -> sb.append(s + ", "));

		sb.deleteCharAt(sb.length() - 1);
		sb.append(")");

		return sb.toString();
	}

	/**
	 * Retrieve the size of the wrapped list
	 * 
	 * @return The size of the wrapped list
	 */
	public int getSize() {
		return wrap.size();
	}

	/**
	 * Partition this list into a list of sublists
	 * 
	 * @param nPerPart
	 *            The size of elements to put into each one of the sublists
	 * @return A list partitioned into partitions of size nPerPart
	 */
	public FunctionalList<FunctionalList<E>> partition(int nPerPart) {
		FunctionalList<FunctionalList<E>> ret = new FunctionalList<>();

		GenHolder<FunctionalList<E>> currPart = new GenHolder<>(
				new FunctionalList<>());

		this.forEach((val) -> {
			if (currPart.unwrap((vl) -> vl.getSize() >= nPerPart)) {
				ret.add(currPart.unwrap((vl) -> vl));
				currPart.transform((vl) -> new FunctionalList<>());
			} else {
				currPart.unwrap((vl) -> vl.add(val));
			}
		});

		return ret;
	}
}