diff options
| author | bculkin2442 <bjculkin@mix.wvu.edu> | 2017-02-09 11:50:31 -0500 |
|---|---|---|
| committer | bculkin2442 <bjculkin@mix.wvu.edu> | 2017-02-09 11:50:31 -0500 |
| commit | d2af58b0f68ebfbba2be7e7679efec6c8c0af12f (patch) | |
| tree | 2b16fbf014db350126e8c1b5f081312276f85f62 | |
| parent | 187e1815488e3c1ed22e7592f304e632cffefb82 (diff) | |
Update
54 files changed, 927 insertions, 1307 deletions
diff --git a/BJC-Utils2/src/examples/java/bjc/utils/examples/BinarySearchTest.java b/BJC-Utils2/src/examples/java/bjc/utils/examples/BinarySearchTest.java index c453e4b..1beaeec 100644 --- a/BJC-Utils2/src/examples/java/bjc/utils/examples/BinarySearchTest.java +++ b/BJC-Utils2/src/examples/java/bjc/utils/examples/BinarySearchTest.java @@ -12,17 +12,17 @@ import bjc.utils.funcdata.bst.TreeLinearizationMethod; * */ public class BinarySearchTest { - private static void displayTree(BinarySearchTree<Character> tree, - Scanner inputSource) { + private static void display(BinarySearchTree<Character> tree, + Scanner input) { System.out.print( "What order would you like the tree to be printed in (m for options): "); char command; while (true) { - command = inputSource.nextLine().charAt(0); + command = input.nextLine().charAt(0); - TreeLinearizationMethod linearizationMethod = null; + TreeLinearizationMethod method = null; switch (command) { case 'm': @@ -36,23 +36,23 @@ public class BinarySearchTest { break; case 'p': - linearizationMethod = TreeLinearizationMethod.PREORDER; + method = TreeLinearizationMethod.PREORDER; break; case 'i': - linearizationMethod = TreeLinearizationMethod.INORDER; + method = TreeLinearizationMethod.INORDER; break; case 'o': - linearizationMethod = TreeLinearizationMethod.POSTORDER; + method = TreeLinearizationMethod.POSTORDER; break; default: System.out.println("ERROR: Unknown command."); } - if (linearizationMethod != null) { - tree.traverse(linearizationMethod, (element) -> { + if (method != null) { + tree.traverse(method, (element) -> { System.out.println("Node: " + element); return true; }); @@ -72,18 +72,18 @@ public class BinarySearchTest { * Unused CLI args */ public static void main(String[] args) { - Scanner inputSource = new Scanner(System.in); + Scanner input = new Scanner(System.in); System.out.println("Binary Tree Constructor/Searcher"); char command = ' '; - BinarySearchTree<Character> searchTree = new BinarySearchTree<>( + BinarySearchTree<Character> tree = new BinarySearchTree<>( (o1, o2) -> o1 - o2); while (command != 'e') { System.out.print("Enter a command (m for help): "); - command = inputSource.nextLine().charAt(0); + command = input.nextLine().charAt(0); switch (command) { case 'm': @@ -106,39 +106,39 @@ public class BinarySearchTest { case 'a': System.out.print( "Enter the letter to add to the binary tree: "); - command = inputSource.nextLine().charAt(0); + command = input.nextLine().charAt(0); - searchTree.addNode(command); + tree.addNode(command); break; case 'r': System.out.print( "Enter the letter to add to the binary tree: "); - command = inputSource.nextLine().charAt(0); + command = input.nextLine().charAt(0); - searchTree.deleteNode(command); + tree.deleteNode(command); break; case 'd': - displayTree(searchTree, inputSource); + display(tree, input); break; case 'f': System.out.print( "Enter the letter to add to the binary tree: "); - command = inputSource.nextLine().charAt(0); + command = input.nextLine().charAt(0); System.out.println("Node " + command + " was " - + (searchTree.isInTree(command) ? "" : "not ") + + (tree.isInTree(command) ? "" : "not ") + "found"); break; case 't': - searchTree.trim(); + tree.trim(); break; case 'b': - searchTree.balance(); + tree.balance(); break; default: @@ -146,6 +146,6 @@ public class BinarySearchTest { } } - inputSource.close(); + input.close(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java index 53428d9..f20139e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/LazyPair.java @@ -14,8 +14,6 @@ import java.util.function.Supplier; * @param <RightType> * The type on the right side of the pair * - * @TODO ensure we don't have any issues with values being materialized - * more than once */ public class LazyPair<LeftType, RightType> implements IPair<LeftType, RightType> { @@ -54,6 +52,7 @@ public class LazyPair<LeftType, RightType> */ public LazyPair(Supplier<LeftType> leftSupp, Supplier<RightType> rightSupp) { + // Use single suppliers to catch double-instantiation bugs leftSupplier = new SingleSupplier<>(leftSupp); rightSupplier = new SingleSupplier<>(rightSupp); @@ -63,14 +62,12 @@ public class LazyPair<LeftType, RightType> @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<LeftType, RightType, - IPair<BoundLeft, BoundRight>> binder) { + BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { return new BoundLazyPair<>(leftSupplier, rightSupplier, binder); } @Override - public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + public <BoundLeft> IPair<BoundLeft, RightType> bindLeft(Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { Supplier<LeftType> leftSupp = () -> { if (leftMaterialized) { return leftValue; diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java b/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java index fc6180b..e7ae1fc 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/ListHolder.java @@ -39,40 +39,35 @@ public class ListHolder<ContainedType> implements IHolder<ContainedType> { } @Override - public <BoundType> IHolder<BoundType> bind( - Function<ContainedType, IHolder<BoundType>> binder) { + public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { IList<IHolder<BoundType>> boundValues = heldValues.map(binder); return new BoundListHolder<>(boundValues); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift( - Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { return (val) -> { return new ListHolder<>(new FunctionalList<>(func.apply(val))); }; } @Override - public <MappedType> IHolder<MappedType> map( - Function<ContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { IList<MappedType> mappedValues = heldValues.map(mapper); return new ListHolder<>(mappedValues); } @Override - public IHolder<ContainedType> transform( - UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { heldValues = heldValues.map(transformer); return this; } @Override - public <UnwrappedType> UnwrappedType unwrap( - Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { return unwrapper.apply(heldValues.randItem()); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Option.java b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java index 16d90e3..33b6327 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Option.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Option.java @@ -17,16 +17,15 @@ public class Option<ContainedType> implements IHolder<ContainedType> { /** * Create a new optional, using the given initial value * - * @param seedValue + * @param seed * The initial value for the optional */ - public Option(ContainedType seedValue) { - held = seedValue; + public Option(ContainedType seed) { + held = seed; } @Override - public <BoundType> IHolder<BoundType> bind( - Function<ContainedType, IHolder<BoundType>> binder) { + public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { if (held == null) { return new Option<>(null); } @@ -35,16 +34,14 @@ public class Option<ContainedType> implements IHolder<ContainedType> { } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift( - Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { return (val) -> { return new Option<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map( - Function<ContainedType, MappedType> mapper) { + public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { if (held == null) { return new Option<>(null); } @@ -53,8 +50,7 @@ public class Option<ContainedType> implements IHolder<ContainedType> { } @Override - public IHolder<ContainedType> transform( - UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { if (held != null) { held = transformer.apply(held); } @@ -63,8 +59,7 @@ public class Option<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap( - Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { if (held == null) { return null; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java index 3480b2a..74040e8 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Pair.java @@ -13,10 +13,10 @@ import java.util.function.Function; * @param <RightType> * The type of the right value */ -public class Pair<LeftType, RightType> - implements IPair<LeftType, RightType> { +public class Pair<LeftType, RightType> implements IPair<LeftType, RightType> { // The left value private LeftType leftValue; + // The right value private RightType rightValue; @@ -24,6 +24,7 @@ public class Pair<LeftType, RightType> * Create a new pair with both sides set to null */ public Pair() { + } /** @@ -41,8 +42,7 @@ public class Pair<LeftType, RightType> @Override public <BoundLeft, BoundRight> IPair<BoundLeft, BoundRight> bind( - BiFunction<LeftType, RightType, - IPair<BoundLeft, BoundRight>> binder) { + BiFunction<LeftType, RightType, IPair<BoundLeft, BoundRight>> binder) { if (binder == null) { throw new NullPointerException("Binder must not be null."); } @@ -51,8 +51,7 @@ public class Pair<LeftType, RightType> } @Override - public <BoundLeft> IPair<BoundLeft, RightType> bindLeft( - Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { + public <BoundLeft> IPair<BoundLeft, RightType> bindLeft(Function<LeftType, IPair<BoundLeft, RightType>> leftBinder) { if (leftBinder == null) { throw new NullPointerException("Binder must not be null"); } @@ -61,8 +60,7 @@ public class Pair<LeftType, RightType> } @Override - public <BoundRight> IPair<LeftType, BoundRight> bindRight( - Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { + public <BoundRight> IPair<LeftType, BoundRight> bindRight(Function<RightType, IPair<LeftType, BoundRight>> rightBinder) { if (rightBinder == null) { throw new NullPointerException("Binder must not be null"); } @@ -71,22 +69,17 @@ public class Pair<LeftType, RightType> } @Override - public <OtherLeft, OtherRight, CombinedLeft, - CombinedRight> IPair<CombinedLeft, CombinedRight> combine( - IPair<OtherLeft, OtherRight> otherPair, - BiFunction<LeftType, OtherLeft, - CombinedLeft> leftCombiner, - BiFunction<RightType, OtherRight, - CombinedRight> rightCombiner) { - return otherPair.bind((otherLeft, otherRight) -> { - return new Pair<>(leftCombiner.apply(leftValue, otherLeft), - rightCombiner.apply(rightValue, otherRight)); - }); + public <OtherLeft, OtherRight, CombinedLeft, CombinedRight> IPair<CombinedLeft, CombinedRight> combine( + IPair<OtherLeft, OtherRight> otherPair, + BiFunction<LeftType, OtherLeft, CombinedLeft> leftCombiner, + BiFunction<RightType, OtherRight, CombinedRight> rightCombiner) { + return otherPair.bind((otherLeft, otherRight) -> { + return new Pair<>(leftCombiner.apply(leftValue, otherLeft), rightCombiner.apply(rightValue, otherRight)); + }); } @Override - public <NewLeft> IPair<NewLeft, RightType> mapLeft( - Function<LeftType, NewLeft> mapper) { + public <NewLeft> IPair<NewLeft, RightType> mapLeft(Function<LeftType, NewLeft> mapper) { if (mapper == null) { throw new NullPointerException("Mapper must not be null"); } @@ -95,8 +88,7 @@ public class Pair<LeftType, RightType> } @Override - public <NewRight> IPair<LeftType, NewRight> mapRight( - Function<RightType, NewRight> mapper) { + public <NewRight> IPair<LeftType, NewRight> mapRight(Function<RightType, NewRight> mapper) { if (mapper == null) { throw new NullPointerException("Mapper must not be null"); } @@ -105,8 +97,7 @@ public class Pair<LeftType, RightType> } @Override - public <MergedType> MergedType merge( - BiFunction<LeftType, RightType, MergedType> merger) { + public <MergedType> MergedType merge(BiFunction<LeftType, RightType, MergedType> merger) { if (merger == null) { throw new NullPointerException("Merger must not be null"); } @@ -116,7 +107,6 @@ public class Pair<LeftType, RightType> @Override public String toString() { - return "pair[l=" + leftValue.toString() + ", r=" - + rightValue.toString() + "]"; + return "pair[l=" + leftValue.toString() + ", r=" + rightValue.toString() + "]"; } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java index ad00496..b5ff1e3 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/SingleSupplier.java @@ -55,8 +55,7 @@ public class SingleSupplier<T> implements Supplier<T> { gotten = true; try { - throw new IllegalStateException( - "Previous instantiation here."); + throw new IllegalStateException("Previous instantiation here."); } catch (IllegalStateException isex) { instSite = isex; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformResult.java b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformResult.java index a2448d2..e72cdf6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformResult.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/TopDownTransformResult.java @@ -8,7 +8,7 @@ package bjc.utils.data; */ public enum TopDownTransformResult { /** - * Do not do anything to this node, and ignore it's children + * Do not do anything to this node, and ignore its children */ SKIP, /** @@ -20,7 +20,7 @@ public enum TopDownTransformResult { */ PASSTHROUGH, /** - * Traverse this nodes children, then transform it + * Traverse the nodes of this children, then transform it */ PUSHDOWN, /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java b/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java index 46fb1a6..b812650 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/Tree.java @@ -19,20 +19,19 @@ import bjc.utils.funcutils.StringUtils; */ public class Tree<ContainedType> implements ITree<ContainedType> { private ContainedType data; - private IList<ITree<ContainedType>> children; + private IList<ITree<ContainedType>> children; private boolean hasChildren; - private int childCount = 0; /** * Create a new leaf node in a tree * - * @param leafToken + * @param leaf * The data to store as a leaf node */ - public Tree(ContainedType leafToken) { - data = leafToken; + public Tree(ContainedType leaf) { + data = leaf; hasChildren = false; } @@ -40,14 +39,13 @@ public class Tree<ContainedType> implements ITree<ContainedType> { /** * Create a new tree node with the specified children * - * @param leafToken + * @param leaf * The data to hold in this node * @param childrn * A list of children for this node */ - public Tree(ContainedType leafToken, - IList<ITree<ContainedType>> childrn) { - data = leafToken; + public Tree(ContainedType leaf, IList<ITree<ContainedType>> childrn) { + data = leaf; hasChildren = true; @@ -59,14 +57,14 @@ public class Tree<ContainedType> implements ITree<ContainedType> { /** * Create a new tree node with the specified children * - * @param leafToken + * @param leaf * The data to hold in this node * @param childrn * A list of children for this node */ @SafeVarargs - public Tree(ContainedType leafToken, ITree<ContainedType>... childrn) { - data = leafToken; + public Tree(ContainedType leaf, ITree<ContainedType>... childrn) { + data = leaf; hasChildren = true; @@ -97,12 +95,10 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public <NewType, ReturnedType> ReturnedType collapse( Function<ContainedType, NewType> leafTransform, - Function<ContainedType, - Function<IList<NewType>, NewType>> nodeCollapser, + Function<ContainedType, Function<IList<NewType>, NewType>> nodeCollapser, Function<NewType, ReturnedType> resultTransformer) { - return resultTransformer - .apply(internalCollapse(leafTransform, nodeCollapser)); + return resultTransformer.apply(internalCollapse(leafTransform, nodeCollapser)); } @Override @@ -111,8 +107,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public ITree<ContainedType> flatMapTree( - Function<ContainedType, ITree<ContainedType>> mapper) { + public ITree<ContainedType> flatMapTree(Function<ContainedType, ITree<ContainedType>> mapper) { if (hasChildren) { ITree<ContainedType> flatMappedData = mapper.apply(data); @@ -132,17 +127,14 @@ public class Tree<ContainedType> implements ITree<ContainedType> { protected <NewType> NewType internalCollapse( Function<ContainedType, NewType> leafTransform, - Function<ContainedType, - Function<IList<NewType>, NewType>> nodeCollapser) { + Function<ContainedType, Function<IList<NewType>, NewType>> nodeCollapser) { if (hasChildren) { - Function<IList<NewType>, - NewType> nodeTransformer = nodeCollapser.apply(data); + Function<IList<NewType>, NewType> nodeTransformer = nodeCollapser.apply(data); - IList<NewType> collapsedChildren = (IList<NewType>) children - .map((child) -> { - return child.collapse(leafTransform, nodeCollapser, - (subTreeVal) -> subTreeVal); - }); + IList<NewType> collapsedChildren = (IList<NewType>) children.map((child) -> { + return child.collapse(leafTransform, nodeCollapser, + (subTreeVal) -> subTreeVal); + }); return nodeTransformer.apply(collapsedChildren); } @@ -150,8 +142,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { return leafTransform.apply(data); } - protected void internalToString(StringBuilder builder, int indentLevel, - boolean initial) { + protected void internalToString(StringBuilder builder, int indentLevel, boolean initial) { if (!initial) { StringUtils.indentNLevels(builder, indentLevel); } @@ -162,8 +153,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { if (hasChildren) { children.forEach((child) -> { - ((Tree<ContainedType>) child).internalToString(builder, - indentLevel + 2, false); + ((Tree<ContainedType>) child).internalToString(builder, indentLevel + 2, false); }); } } @@ -173,25 +163,21 @@ public class Tree<ContainedType> implements ITree<ContainedType> { Function<ContainedType, MappedType> leafTransformer, Function<ContainedType, MappedType> operatorTransformer) { if (hasChildren) { - IList<ITree<MappedType>> mappedChildren = children - .map((child) -> { - return child.rebuildTree(leafTransformer, - operatorTransformer); - }); + IList<ITree<MappedType>> mappedChildren = children.map((child) -> { + return child.rebuildTree(leafTransformer, + operatorTransformer); + }); - return new Tree<>(operatorTransformer.apply(data), - mappedChildren); + return new Tree<>(operatorTransformer.apply(data), mappedChildren); } return new Tree<>(leafTransformer.apply(data)); } @Override - public void selectiveTransform(Predicate<ContainedType> nodePicker, - UnaryOperator<ContainedType> transformer) { + public void selectiveTransform(Predicate<ContainedType> nodePicker, UnaryOperator<ContainedType> transformer) { if (hasChildren) { - children.forEach((child) -> child - .selectiveTransform(nodePicker, transformer)); + children.forEach((child) -> child.selectiveTransform(nodePicker, transformer)); } else { data = transformer.apply(data); } @@ -199,11 +185,9 @@ public class Tree<ContainedType> implements ITree<ContainedType> { @Override public ITree<ContainedType> topDownTransform( - Function<ContainedType, - TopDownTransformResult> transformPicker, + Function<ContainedType, TopDownTransformResult> transformPicker, UnaryOperator<ITree<ContainedType>> transformer) { - TopDownTransformResult transformResult = transformPicker - .apply(data); + TopDownTransformResult transformResult = transformPicker.apply(data); switch (transformResult) { case PASSTHROUGH: @@ -211,8 +195,7 @@ public class Tree<ContainedType> implements ITree<ContainedType> { if (hasChildren) { children.forEach((child) -> { - result.addChild(child.topDownTransform( - transformPicker, transformer)); + result.addChild(child.topDownTransform(transformPicker, transformer)); }); } @@ -226,28 +209,23 @@ public class Tree<ContainedType> implements ITree<ContainedType> { if (hasChildren) { children.forEach((child) -> { - result.addChild(child.topDownTransform( - transformPicker, transformer)); + result.addChild(child.topDownTransform(transformPicker, transformer)); }); } return transformer.apply(result); case PULLUP: - ITree<ContainedType> intermediateResult = transformer - .apply(this); + ITree<ContainedType> intermediateResult = transformer.apply(this); result = new Tree<>(intermediateResult.getHead()); intermediateResult.doForChildren((child) -> { - result.addChild(child.topDownTransform(transformPicker, - transformer)); + result.addChild(child.topDownTransform(transformPicker, transformer)); }); return result; default: - throw new IllegalArgumentException( - "Recieved unknown transform result " - + transformResult); + throw new IllegalArgumentException("Recieved unknown transform result " + transformResult); } } @@ -264,66 +242,55 @@ public class Tree<ContainedType> implements ITree<ContainedType> { } @Override - public <TransformedType> TransformedType transformChild(int childNo, - Function<ITree<ContainedType>, TransformedType> transformer) { + public <TransformedType> TransformedType transformChild( + int childNo, Function<ITree<ContainedType>, TransformedType> transformer) { if (childNo < 0 || childNo > (childCount - 1)) { - throw new IllegalArgumentException( - "Child index #" + childNo + " is invalid"); + throw new IllegalArgumentException("Child index #" + childNo + " is invalid"); } return transformer.apply(children.getByIndex(childNo)); } @Override - public <TransformedType> TransformedType transformHead( - Function<ContainedType, TransformedType> transformer) { + public <TransformedType> TransformedType transformHead(Function<ContainedType, TransformedType> transformer) { return transformer.apply(data); } @Override - public <MappedType> ITree<MappedType> transformTree( - Function<ContainedType, MappedType> transformer) { + public <MappedType> ITree<MappedType> transformTree(Function<ContainedType, MappedType> transformer) { if (hasChildren) { - IList<ITree<MappedType>> transformedChildren = children - .map((child) -> child.transformTree(transformer)); + IList<ITree<MappedType>> transformedChildren = children.map((child) -> child.transformTree(transformer)); - return new Tree<>(transformer.apply(data), - transformedChildren); + return new Tree<>(transformer.apply(data), transformedChildren); } return new Tree<>(transformer.apply(data)); } @Override - public void traverse(TreeLinearizationMethod linearizationMethod, - Consumer<ContainedType> action) { + public void traverse(TreeLinearizationMethod linearizationMethod, Consumer<ContainedType> action) { if (hasChildren) { switch (linearizationMethod) { case INORDER: if (childCount != 2) { - throw new IllegalArgumentException( - "Can only do in-order traversal for binary trees."); + throw new IllegalArgumentException("Can only do in-order traversal for binary trees."); } - children.getByIndex(0).traverse(linearizationMethod, - action); + children.getByIndex(0).traverse(linearizationMethod, action); action.accept(data); - children.getByIndex(1).traverse(linearizationMethod, - action); + children.getByIndex(1).traverse(linearizationMethod, action); break; case POSTORDER: - children.forEach((child) -> child - .traverse(linearizationMethod, action)); + children.forEach((child) -> child.traverse(linearizationMethod, action)); action.accept(data); break; case PREORDER: action.accept(data); - children.forEach((child) -> child - .traverse(linearizationMethod, action)); + children.forEach((child) -> child.traverse(linearizationMethod, action)); break; default: break; diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/WrappedLazy.java b/BJC-Utils2/src/main/java/bjc/utils/data/WrappedLazy.java index b894ac7..d278358 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/WrappedLazy.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/WrappedLazy.java @@ -12,46 +12,37 @@ class WrappedLazy<ContainedType> implements IHolder<ContainedType> { // This has an extra parameter, because otherwise it erases to the same // as the public one - private WrappedLazy(IHolder<IHolder<ContainedType>> wrappedHolder, - boolean dummy) { + private WrappedLazy(IHolder<IHolder<ContainedType>> wrappedHolder, boolean dummy) { held = wrappedHolder; } @Override - public <BoundType> IHolder<BoundType> bind( - Function<ContainedType, IHolder<BoundType>> binder) { - IHolder<IHolder<BoundType>> newHolder = held - .map((containedHolder) -> { - return containedHolder.bind(binder); - }); + public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { + IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { + return containedHolder.bind(binder); + }); return new WrappedLazy<>(newHolder, false); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift( - Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { return (val) -> { return new Lazy<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map( - Function<ContainedType, MappedType> mapper) { - IHolder<IHolder<MappedType>> newHolder = held - .map((containedHolder) -> { - return containedHolder.map(mapper); - }); + public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { + IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { + return containedHolder.map(mapper); + }); return new WrappedLazy<>(newHolder, false); } @Override - public IHolder<ContainedType> transform( - UnaryOperator<ContainedType> transformer) { - // FIXME this smells bad to me, but I can't figure out how else to - // do it + public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { held.transform((containedHolder) -> { return containedHolder.transform(transformer); }); @@ -60,8 +51,7 @@ class WrappedLazy<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap( - Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { return held.unwrap((containedHolder) -> { return containedHolder.unwrap(unwrapper); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/data/WrappedOption.java b/BJC-Utils2/src/main/java/bjc/utils/data/WrappedOption.java index fea4cb9..554eb54 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/data/WrappedOption.java +++ b/BJC-Utils2/src/main/java/bjc/utils/data/WrappedOption.java @@ -10,56 +10,48 @@ class WrappedOption<ContainedType> implements IHolder<ContainedType> { held = new Option<>(seedValue); } - private WrappedOption(IHolder<IHolder<ContainedType>> toHold, - boolean dummy) { + private WrappedOption(IHolder<IHolder<ContainedType>> toHold, boolean dummy) { held = toHold; } - @Override - public <BoundType> IHolder<BoundType> bind( - Function<ContainedType, IHolder<BoundType>> binder) { - IHolder<IHolder<BoundType>> newHolder = held - .map((containedHolder) -> { - return containedHolder.bind((containedValue) -> { - if (containedValue == null) { - return new Option<>(null); - } - - return binder.apply(containedValue); - }); - }); + @Override public <BoundType> IHolder<BoundType> bind(Function<ContainedType, IHolder<BoundType>> binder) { + IHolder<IHolder<BoundType>> newHolder = held.map((containedHolder) -> { + return containedHolder.bind((containedValue) -> { + if (containedValue == null) { + return new Option<>(null); + } + + return binder.apply(containedValue); + }); + }); return new WrappedOption<>(newHolder, false); } @Override - public <NewType> Function<ContainedType, IHolder<NewType>> lift( - Function<ContainedType, NewType> func) { + public <NewType> Function<ContainedType, IHolder<NewType>> lift(Function<ContainedType, NewType> func) { return (val) -> { return new Option<>(func.apply(val)); }; } @Override - public <MappedType> IHolder<MappedType> map( - Function<ContainedType, MappedType> mapper) { - IHolder<IHolder<MappedType>> newHolder = held - .map((containedHolder) -> { - return containedHolder.map((containedValue) -> { - if (containedValue == null) { - return null; - } - - return mapper.apply(containedValue); - }); - }); + public <MappedType> IHolder<MappedType> map(Function<ContainedType, MappedType> mapper) { + IHolder<IHolder<MappedType>> newHolder = held.map((containedHolder) -> { + return containedHolder.map((containedValue) -> { + if (containedValue == null) { + return null; + } + + return mapper.apply(containedValue); + }); + }); return new WrappedOption<>(newHolder, false); } @Override - public IHolder<ContainedType> transform( - UnaryOperator<ContainedType> transformer) { + public IHolder<ContainedType> transform(UnaryOperator<ContainedType> transformer) { held.transform((containedHolder) -> { return containedHolder.transform((containedValue) -> { if (containedValue == null) { @@ -74,8 +66,7 @@ class WrappedOption<ContainedType> implements IHolder<ContainedType> { } @Override - public <UnwrappedType> UnwrappedType unwrap( - Function<ContainedType, UnwrappedType> unwrapper) { + public <UnwrappedType> UnwrappedType unwrap(Function<ContainedType, UnwrappedType> unwrapper) { return held.unwrap((containedHolder) -> { return containedHolder.unwrap((containedValue) -> { if (containedValue == null) { diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java index b902207..81c263f 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalList.java @@ -19,7 +19,9 @@ 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 + * over it. + * + * Differs from a stream in every way except for the fact that * they both provide functional operations. * * @author ben @@ -28,16 +30,16 @@ import bjc.utils.data.Pair; * The type in this list */ public class FunctionalList<E> implements Cloneable, IList<E> { - /** + /* * The list used as a backing store */ - private List<E> wrappedList; + private List<E> wrapped; /** * Create a new empty functional list. */ public FunctionalList() { - wrappedList = new ArrayList<>(); + wrapped = new ArrayList<>(); } /** @@ -50,10 +52,10 @@ public class FunctionalList<E> implements Cloneable, IList<E> { */ @SafeVarargs public FunctionalList(E... items) { - wrappedList = new ArrayList<>(items.length); + wrapped = new ArrayList<>(items.length); for (E item : items) { - wrappedList.add(item); + wrapped.add(item); } } @@ -64,7 +66,7 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * The size of the backing list . */ private FunctionalList(int size) { - wrappedList = new ArrayList<>(size); + wrapped = new ArrayList<>(size); } /** @@ -72,42 +74,31 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * * Takes O(1) time, since it doesn't copy the list. * - * @param backingList + * @param backing * The list to use as a backing list. */ - public FunctionalList(List<E> backingList) { - if (backingList == null) { + public FunctionalList(List<E> backing) { + if (backing == null) { throw new NullPointerException( "Backing list must be non-null"); } - wrappedList = backingList; + wrapped = backing; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#add(E) - */ @Override public boolean add(E item) { - return wrappedList.add(item); + return wrapped.add(item); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#allMatch(java.util.function. - * Predicate) - */ @Override - public boolean allMatch(Predicate<E> matchPredicate) { - if (matchPredicate == null) { + public boolean allMatch(Predicate<E> predicate) { + if (predicate == null) { throw new NullPointerException("Predicate must be non-null"); } - for (E item : wrappedList) { - if (!matchPredicate.test(item)) { + for (E item : wrapped) { + if (!predicate.test(item)) { // We've found a non-matching item return false; } @@ -117,20 +108,14 @@ public class FunctionalList<E> implements Cloneable, IList<E> { return true; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#anyMatch(java.util.function. - * Predicate) - */ @Override - public boolean anyMatch(Predicate<E> matchPredicate) { - if (matchPredicate == null) { + public boolean anyMatch(Predicate<E> predicate) { + if (predicate == null) { throw new NullPointerException("Predicate must be not null"); } - for (E item : wrappedList) { - if (matchPredicate.test(item)) { + for (E item : wrapped) { + if (predicate.test(item)) { // We've found a matching item return true; } @@ -149,127 +134,87 @@ public class FunctionalList<E> implements Cloneable, IList<E> { */ @Override public IList<E> clone() { - IList<E> clonedList = new FunctionalList<>(); + IList<E> cloned = new FunctionalList<>(); - for (E element : wrappedList) { - clonedList.add(element); + for (E element : wrapped) { + cloned.add(element); } - return clonedList; + return cloned; } - /* - * (non-Javadoc) - * - * @see - * bjc.utils.funcdata.IFunctionalList#combineWith(bjc.utils.funcdata. - * IFunctionalList, java.util.function.BiFunction) - */ @Override public <T, F> IList<F> combineWith(IList<T> rightList, BiFunction<E, T, F> itemCombiner) { if (rightList == null) { - throw new NullPointerException( - "Target combine list must not be null"); + throw new NullPointerException( "Target combine list must not be null"); } else if (itemCombiner == null) { throw new NullPointerException("Combiner must not be null"); } - IList<F> returnedList = new FunctionalList<>(); + IList<F> returned = new FunctionalList<>(); // Get the iterator for the other list Iterator<T> rightIterator = rightList.toIterable().iterator(); - for (Iterator<E> leftIterator = wrappedList.iterator(); + for (Iterator<E> leftIterator = wrapped.iterator(); leftIterator.hasNext() && rightIterator.hasNext();) { // Add the transformed items to the result list E leftVal = leftIterator.next(); T rightVal = rightIterator.next(); - returnedList.add(itemCombiner.apply(leftVal, rightVal)); + returned.add(itemCombiner.apply(leftVal, rightVal)); } - return returnedList; + return returned; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#contains(E) - */ @Override public boolean contains(E item) { // Check if any items in the list match the provided item return this.anyMatch(item::equals); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#first() - */ @Override public E first() { - if (wrappedList.size() < 1) { - throw new NoSuchElementException( - "Attempted to get first element of empty list"); + if (wrapped.size() < 1) { + throw new NoSuchElementException("Attempted to get first element of empty list"); } - return wrappedList.get(0); + return wrapped.get(0); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#flatMap(java.util.function. - * Function) - */ @Override - public <T> IList<T> flatMap(Function<E, IList<T>> elementExpander) { - if (elementExpander == null) { + public <T> IList<T> flatMap(Function<E, IList<T>> expander) { + if (expander == null) { throw new NullPointerException("Expander must not be null"); } - IList<T> returnedList = new FunctionalList<>( - this.wrappedList.size()); + IList<T> returned = new FunctionalList<>(this.wrapped.size()); forEach(element -> { - IList<T> expandedElement = elementExpander.apply(element); + IList<T> expandedElement = expander.apply(element); if (expandedElement == null) { - throw new NullPointerException( - "Expander returned null list"); + throw new NullPointerException("Expander returned null list"); } // Add each element to the returned list - expandedElement.forEach(returnedList::add); + expandedElement.forEach(returned::add); }); - return returnedList; + return returned; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#forEach(java.util.function. - * Consumer) - */ @Override public void forEach(Consumer<E> action) { if (action == null) { throw new NullPointerException("Action is null"); } - wrappedList.forEach(action); + wrapped.forEach(action); } - /* - * (non-Javadoc) - * - * @see - * bjc.utils.funcdata.IFunctionalList#forEachIndexed(java.util.function - * .BiConsumer) - */ @Override public void forEachIndexed(BiConsumer<Integer, E> indexedAction) { if (indexedAction == null) { @@ -279,24 +224,18 @@ public class FunctionalList<E> implements Cloneable, IList<E> { // This is held b/c ref'd variables must be final/effectively final IHolder<Integer> currentIndex = new Identity<>(0); - wrappedList.forEach((element) -> { + wrapped.forEach((element) -> { // Call the action with the index and the value - indexedAction.accept(currentIndex.unwrap(index -> index), - element); + indexedAction.accept(currentIndex.unwrap(index -> index), element); // Increment the value currentIndex.transform((index) -> index + 1); }); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#getByIndex(int) - */ @Override public E getByIndex(int index) { - return wrappedList.get(index); + return wrapped.get(index); } /** @@ -305,52 +244,35 @@ public class FunctionalList<E> implements Cloneable, IList<E> { * @return The backing list this list is based off of. */ public List<E> getInternal() { - return wrappedList; + return wrapped; } - /* - * (non-Javadoc) - * - * @see - * bjc.utils.funcdata.IFunctionalList#getMatching(java.util.function. - * Predicate) - */ @Override - public IList<E> getMatching(Predicate<E> matchPredicate) { - if (matchPredicate == null) { + public IList<E> getMatching(Predicate<E> predicate) { + if (predicate == null) { throw new NullPointerException("Predicate must not be null"); } - IList<E> returnedList = new FunctionalList<>(); + IList<E> returned = new FunctionalList<>(); - wrappedList.forEach((element) -> { - if (matchPredicate.test(element)) { + wrapped.forEach((element) -> { + if (predicate.test(element)) { // The item matches, so add it to the returned list - returnedList.add(element); + returned.add(element); } }); - return returnedList; + return returned; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#getSize() - */ @Override public int getSize() { - return wrappedList.size(); + return wrapped.size(); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#isEmpty() - */ @Override public boolean isEmpty() { - return wrappedList.isEmpty(); + return wrapped.isEmpty(); } /* @@ -358,59 +280,40 @@ public class FunctionalList<E> implements Cloneable, IList<E> { */ private Boolean isPartitionFull(int numberPerPartition, IHolder<IList<E>> currentPartition) { - return currentPartition.unwrap( - (partition) -> partition.getSize() >= numberPerPartition); + return currentPartition.unwrap((partition) -> partition.getSize() >= numberPerPartition); } - /* - * (non-Javadoc) - * - * @see - * bjc.utils.funcdata.IFunctionalList#map(java.util.function.Function) - */ @Override public <T> IList<T> map(Function<E, T> elementTransformer) { if (elementTransformer == null) { throw new NullPointerException("Transformer must be not null"); } - IList<T> returnedList = new FunctionalList<>( - this.wrappedList.size()); + IList<T> returned = new FunctionalList<>(this.wrapped.size()); forEach(element -> { // Add the transformed item to the result - returnedList.add(elementTransformer.apply(element)); + returned.add(elementTransformer.apply(element)); }); - return returnedList; + return returned; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#pairWith(bjc.utils.funcdata. - * IFunctionalList) - */ @Override public <T> IList<IPair<E, T>> pairWith(IList<T> rightList) { return combineWith(rightList, Pair<E, T>::new); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#partition(int) - */ @Override public IList<IList<E>> partition(int numberPerPartition) { if (numberPerPartition < 1 - || numberPerPartition > wrappedList.size()) { + || numberPerPartition > wrapped.size()) { throw new IllegalArgumentException("" + numberPerPartition + " is an invalid partition size. Must be between 1 and " - + wrappedList.size()); + + wrapped.size()); } - IList<IList<E>> returnedList = new FunctionalList<>(); + IList<IList<E>> returned = new FunctionalList<>(); // The current partition being filled IHolder<IList<E>> currentPartition = new Identity<>( @@ -419,55 +322,35 @@ public class FunctionalList<E> implements Cloneable, IList<E> { this.forEach((element) -> { if (isPartitionFull(numberPerPartition, currentPartition)) { // Add the partition to the list - returnedList.add( - currentPartition.unwrap((partition) -> partition)); + returned.add(currentPartition.unwrap((partition) -> partition)); // Start a new partition - currentPartition - .transform((partition) -> new FunctionalList<>()); + currentPartition.transform((partition) -> new FunctionalList<>()); } else { // Add the element to the current partition - currentPartition - .unwrap((partition) -> partition.add(element)); + currentPartition.unwrap((partition) -> partition.add(element)); } }); - return returnedList; + return returned; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#prepend(E) - */ @Override public void prepend(E item) { - wrappedList.add(0, item); + wrapped.add(0, item); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#randItem(java.util.Random) - */ @Override public E randItem(Function<Integer, Integer> rnd) { if (rnd == null) { - throw new NullPointerException( - "Random source must not be null"); + throw new NullPointerException("Random source must not be null"); } - int randomIndex = rnd.apply(wrappedList.size()); + int randomIndex = rnd.apply(wrapped.size()); - return wrappedList.get(randomIndex); + return wrapped.get(randomIndex); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#reduceAux(T, - * java.util.function.BiFunction, java.util.function.Function) - */ @Override public <T, F> F reduceAux(T initialValue, BiFunction<E, T, T> stateAccumulator, @@ -481,36 +364,24 @@ public class FunctionalList<E> implements Cloneable, IList<E> { // The current collapsed list IHolder<T> currentState = new Identity<>(initialValue); - wrappedList.forEach(element -> { + wrapped.forEach(element -> { // Accumulate a new value into the state - currentState.transform( - (state) -> stateAccumulator.apply(element, state)); + currentState.transform((state) -> stateAccumulator.apply(element, state)); }); // Convert the state to its final value return currentState.unwrap(resultTransformer); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#removeIf(java.util.function. - * Predicate) - */ @Override public boolean removeIf(Predicate<E> removePredicate) { if (removePredicate == null) { throw new NullPointerException("Predicate must be non-null"); } - return wrappedList.removeIf(removePredicate); + return wrapped.removeIf(removePredicate); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#removeMatching(E) - */ @Override public void removeMatching(E desiredElement) { removeIf((element) -> element.equals(desiredElement)); @@ -518,66 +389,44 @@ public class FunctionalList<E> implements Cloneable, IList<E> { @Override public void reverse() { - Collections.reverse(wrappedList); + Collections.reverse(wrapped); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#search(E, - * java.util.Comparator) - */ @Override public E search(E searchKey, Comparator<E> comparator) { // Search our internal list - int foundIndex = Collections.binarySearch(wrappedList, searchKey, + int foundIndex = Collections.binarySearch(wrapped, searchKey, comparator); if (foundIndex >= 0) { // We found a matching element - return wrappedList.get(foundIndex); + return wrapped.get(foundIndex); } // We didn't find an element return null; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#sort(java.util.Comparator) - */ @Override public void sort(Comparator<E> comparator) { - Collections.sort(wrappedList, comparator); + Collections.sort(wrapped, comparator); } @Override public IList<E> tail() { - return new FunctionalList<>(wrappedList.subList(1, getSize())); + return new FunctionalList<>(wrapped.subList(1, getSize())); } @Override public E[] toArray(E[] arrType) { - return wrappedList.toArray(arrType); + return wrapped.toArray(arrType); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalList#toIterable() - */ @Override public Iterable<E> toIterable() { - return wrappedList; + return wrapped; } - /* - * Reduce this item to a form useful for looking at in the debugger. - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ @Override public String toString() { StringBuilder sb = new StringBuilder("("); @@ -593,4 +442,4 @@ public class FunctionalList<E> implements Cloneable, IList<E> { return sb.toString(); } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java index dfe02dc..cc70ae1 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalMap.java @@ -18,8 +18,7 @@ import bjc.utils.data.IPair; * @param <ValueType> * The type of the map's values */ -public class FunctionalMap<KeyType, ValueType> - implements IMap<KeyType, ValueType> { +public class FunctionalMap<KeyType, ValueType> implements IMap<KeyType, ValueType> { private Map<KeyType, ValueType> wrappedMap; /** @@ -65,11 +64,6 @@ public class FunctionalMap<KeyType, ValueType> wrappedMap.clear(); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalMap#containsKey(K) - */ @Override public boolean containsKey(KeyType key) { return wrappedMap.containsKey(key); @@ -95,11 +89,6 @@ public class FunctionalMap<KeyType, ValueType> wrappedMap.values().forEach(action); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalMap#get(K) - */ @Override public ValueType get(KeyType key) { if (key == null) { @@ -107,8 +96,7 @@ public class FunctionalMap<KeyType, ValueType> } if (!wrappedMap.containsKey(key)) { - throw new IllegalArgumentException( - "Key " + key + " is not present in the map"); + throw new IllegalArgumentException("Key " + key + " is not present in the map"); } return wrappedMap.get(key); @@ -130,12 +118,6 @@ public class FunctionalMap<KeyType, ValueType> return keys; } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalMap#mapValues(java.util.function. - * Function) - */ @Override public <MappedValue> IMap<KeyType, MappedValue> mapValues( Function<ValueType, MappedValue> transformer) { @@ -146,11 +128,6 @@ public class FunctionalMap<KeyType, ValueType> return new TransformedValueMap<>(this, transformer); } - /* - * (non-Javadoc) - * - * @see bjc.utils.funcdata.IFunctionalMap#put(K, V) - */ @Override public ValueType put(KeyType key, ValueType val) { if (key == null) { @@ -180,4 +157,4 @@ public class FunctionalMap<KeyType, ValueType> return values; } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java index 3714bcd..078bba6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/FunctionalStringTokenizer.java @@ -24,11 +24,10 @@ public class FunctionalStringTokenizer { "String to tokenize must be non-null"); } - return new FunctionalStringTokenizer( - new StringTokenizer(strang, " ")); + return new FunctionalStringTokenizer(new StringTokenizer(strang, " ")); } - /** + /* * The string tokenizer being driven */ private StringTokenizer input; @@ -41,8 +40,7 @@ public class FunctionalStringTokenizer { */ public FunctionalStringTokenizer(String inp) { if (inp == null) { - throw new NullPointerException( - "String to tokenize must be non-null"); + throw new NullPointerException("String to tokenize must be non-null"); } this.input = new StringTokenizer(inp); @@ -50,24 +48,22 @@ public class FunctionalStringTokenizer { /** * Create a functional string tokenizer from a given string and set of - * seperators + * separators * - * @param inputString + * @param input * The string to tokenize * @param seperators * The set of separating tokens to use for splitting */ - public FunctionalStringTokenizer(String inputString, + public FunctionalStringTokenizer(String input, String seperators) { - if (inputString == null) { - throw new NullPointerException( - "String to tokenize must not be null"); + if (input == null) { + throw new NullPointerException("String to tokenize must not be null"); } else if (seperators == null) { - throw new NullPointerException( - "Tokens to split on must not be null"); + throw new NullPointerException("Tokens to split on must not be null"); } - this.input = new StringTokenizer(inputString, seperators); + this.input = new StringTokenizer(input, seperators); } /** @@ -78,8 +74,7 @@ public class FunctionalStringTokenizer { */ public FunctionalStringTokenizer(StringTokenizer toWrap) { if (toWrap == null) { - throw new NullPointerException( - "Wrapped tokenizer must not be null"); + throw new NullPointerException("Wrapped tokenizer must not be null"); } this.input = toWrap; @@ -102,7 +97,7 @@ public class FunctionalStringTokenizer { } /** - * Get the string tokenizer encapsuled by this tokenizer + * Get the string tokenizer encapsulated by this tokenizer * * @return The encapsulated tokenizer */ @@ -120,14 +115,15 @@ public class FunctionalStringTokenizer { } /** - * Return the next token from the tokenizer. Returns null if no more - * tokens are available + * Return the next token from the tokenizer. + * + * Returns null if no more tokens are available * * @return The next token from the tokenizer */ public String nextToken() { if (input.hasMoreTokens()) { - // Return the next availible token + // Return the next available token return input.nextToken(); } @@ -151,24 +147,24 @@ public class FunctionalStringTokenizer { * @param <E> * The type of the converted tokens * - * @param tokenTransformer + * @param transformer * The function to use to convert tokens. * @return A list containing all of the converted tokens. */ - public <E> IList<E> toList(Function<String, E> tokenTransformer) { - if (tokenTransformer == null) { + public <E> IList<E> toList(Function<String, E> transformer) { + if (transformer == null) { throw new NullPointerException("Transformer must not be null"); } - IList<E> returnList = new FunctionalList<>(); + IList<E> returned = new FunctionalList<>(); // Add each token to the list after transforming it forEachToken(token -> { - E transformedToken = tokenTransformer.apply(token); + E transformedToken = transformer.apply(token); - returnList.add(transformedToken); + returned.add(transformedToken); }); - return returnList; + return returned; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java index 037b2b6..f920fce 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IList.java @@ -24,7 +24,7 @@ public interface IList<ContainedType> { * * @param item * The item to add to this list. - * @return Whether the item was added to the list succesfully. + * @return Whether the item was added to the list successfully. */ boolean add(ContainedType item); @@ -33,7 +33,7 @@ public interface IList<ContainedType> { * * @param items * The list of items to add - * @return True if every item was succesfully added to the list, false + * @return True if every item was successfully added to the list, false * otherwise */ default boolean addAll(IList<ContainedType> items) { @@ -44,22 +44,22 @@ public interface IList<ContainedType> { * Check if all of the elements of this list match the specified * predicate. * - * @param matchPredicate + * @param matcher * The predicate to use for checking. * @return Whether all of the elements of the list match the specified * predicate. */ - boolean allMatch(Predicate<ContainedType> matchPredicate); + boolean allMatch(Predicate<ContainedType> matcher); /** * Check if any of the elements in this list match the specified list. * - * @param matchPredicate + * @param matcher * The predicate to use for checking. * @return Whether any element in the list matches the provided * predicate. */ - boolean anyMatch(Predicate<ContainedType> matchPredicate); + boolean anyMatch(Predicate<ContainedType> matcher); /** * Reduce the contents of this list using a collector @@ -74,8 +74,7 @@ public interface IList<ContainedType> { */ public default <StateType, ReducedType> ReducedType collect( Collector<ContainedType, StateType, ReducedType> collector) { - BiConsumer<StateType, ContainedType> accumulator = collector - .accumulator(); + BiConsumer<StateType, ContainedType> accumulator = collector.accumulator(); return reduceAux(collector.supplier().get(), (value, state) -> { accumulator.accept(state, value); @@ -86,7 +85,9 @@ public interface IList<ContainedType> { /** * 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. + * 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 @@ -97,15 +98,15 @@ public interface IList<ContainedType> { * @param <CombinedType> * The type of the combined list * - * @param rightList + * @param list * The list to combine with - * @param itemCombiner + * @param combiner * The function to use for combining element pairs. * @return A new list containing the merged pairs of lists. */ <OtherType, CombinedType> IList<CombinedType> combineWith( - IList<OtherType> rightList, - BiFunction<ContainedType, OtherType, CombinedType> itemCombiner); + IList<OtherType> list, + BiFunction<ContainedType, OtherType, CombinedType> combiner); /** * Check if the list contains the specified item @@ -125,18 +126,20 @@ public interface IList<ContainedType> { /** * Apply a function to each member of the list, then flatten the - * results. Does not change the underlying list. + * results. + * + * Does not change the underlying list. * * @param <MappedType> * The type of the flattened list * - * @param elementExpander + * @param expander * The function to apply to each member of the list. * @return A new list containing the flattened results of applying the * provided function. */ <MappedType> IList<MappedType> flatMap( - Function<ContainedType, IList<MappedType>> elementExpander); + Function<ContainedType, IList<MappedType>> expander); /** * Apply a given action for each member of the list @@ -149,11 +152,11 @@ public interface IList<ContainedType> { /** * Apply a given function to each element in the list and its index. * - * @param indexedAction + * @param action * The function to apply to each element in the list and its * index. */ - void forEachIndexed(BiConsumer<Integer, ContainedType> indexedAction); + void forEachIndexed(BiConsumer<Integer, ContainedType> action); /** * Retrieve a value in the list by its index. @@ -167,12 +170,11 @@ public interface IList<ContainedType> { /** * Retrieve a list containing all elements matching a predicate * - * @param matchPredicate + * @param predicate * The predicate to match by * @return A list containing all elements that match the predicate */ - IList<ContainedType> getMatching( - Predicate<ContainedType> matchPredicate); + IList<ContainedType> getMatching(Predicate<ContainedType> predicate); /** * Retrieve the size of the wrapped list @@ -190,17 +192,19 @@ public interface IList<ContainedType> { /** * Create a new list by applying the given function to each element in - * the list. Does not change the underlying list. + * the list. + * + * Does not change the underlying list. * * @param <MappedType> * The type of the transformed list * - * @param elementTransformer + * @param transformer * The function to apply to each element in the list * @return A new list containing the mapped elements of this list. */ <MappedType> IList<MappedType> map( - Function<ContainedType, MappedType> elementTransformer); + Function<ContainedType, MappedType> transformer); /** * Zip two lists into a list of pairs @@ -208,22 +212,21 @@ public interface IList<ContainedType> { * @param <OtherType> * The type of the second list * - * @param rightList + * @param list * The list to use as the left side of the pair * @return A list containing pairs of this element and the specified * list */ - <OtherType> IList<IPair<ContainedType, OtherType>> pairWith( - IList<OtherType> rightList); + <OtherType> IList<IPair<ContainedType, OtherType>> pairWith(IList<OtherType> list); /** * Partition this list into a list of sublists * - * @param numberPerPartition + * @param partitionSize * The size of elements to put into each one of the sublists * @return A list partitioned into partitions of size nPerPart */ - IList<IList<ContainedType>> partition(int numberPerPartition); + IList<IList<ContainedType>> partition(int partitionSize); /** * Prepend an item to the list @@ -261,37 +264,37 @@ public interface IList<ContainedType> { * @param <ReducedType> * The final value type * - * @param initialValue + * @param initial * The initial value of the accumulative state. - * @param stateAccumulator + * @param accumulator * The function to use to combine a list element with the * accumulative state. - * @param resultTransformer + * @param transformer * 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. */ - <StateType, ReducedType> ReducedType reduceAux(StateType initialValue, - BiFunction<ContainedType, StateType, StateType> stateAccumulator, - Function<StateType, ReducedType> resultTransformer); + <StateType, ReducedType> ReducedType reduceAux(StateType initial, + BiFunction<ContainedType, StateType, StateType> accumulator, + Function<StateType, ReducedType> transformer); /** * Remove all elements that match a given predicate * - * @param removePredicate + * @param predicate * The predicate to use to determine elements to delete * @return Whether there was anything that satisfied the predicate */ - boolean removeIf(Predicate<ContainedType> removePredicate); + boolean removeIf(Predicate<ContainedType> predicate); /** * Remove all parameters that match a given parameter * - * @param desiredElement + * @param element * The object to remove all matching copies of */ - void removeMatching(ContainedType desiredElement); + void removeMatching(ContainedType element); /** * Reverse the contents of this list in place @@ -300,22 +303,25 @@ public interface IList<ContainedType> { /** * 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. + * means of comparing elements. + * + * Since this IS a binary search, the list must have been sorted before hand. * - * @param searchKey + * @param key * The key to search for. * @param comparator * The way to compare elements for searching. Pass null to * use the natural ordering for E * @return The element if it is in this list, or null if it is not. */ - ContainedType search(ContainedType searchKey, + ContainedType search(ContainedType key, Comparator<ContainedType> comparator); /** * Sort the elements of this list using the provided way of comparing - * elements. Does change the underlying list. + * elements. + * + * Does change the underlying list. * * @param comparator * The way to compare elements for sorting. Pass null to use @@ -333,16 +339,16 @@ public interface IList<ContainedType> { /** * Convert this list into an array * - * @param arrType + * @param type * The type of array to return * @return The list, as an array */ - public ContainedType[] toArray(ContainedType[] arrType); + public ContainedType[] toArray(ContainedType[] type); /** - * Convert the list into a iterable + * Convert the list into a Iterable * * @return An iterable view onto the list */ public Iterable<ContainedType> toIterable(); -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java index e69495a..9e74628 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/IMap.java @@ -146,7 +146,7 @@ public interface IMap<KeyType, ValueType> { * @param key * The key to remove from the map * @return The previous value for the key in the map, or null if the - * key wasn't in the class. NOTE: Just because you recieved + * key wasn't in the class. NOTE: Just because you received * null, doesn't mean the map wasn't changed. It may mean that * someone put a null value for that key into the map */ @@ -158,4 +158,4 @@ public interface IMap<KeyType, ValueType> { * @return A list of values in this map */ IList<ValueType> valueList(); -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java index d43e8d5..c87c34b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/TransformedValueMap.java @@ -18,23 +18,23 @@ import java.util.function.Function; */ final class TransformedValueMap<OldKey, OldValue, NewValue> implements IMap<OldKey, NewValue> { - private IMap<OldKey, OldValue> mapToTransform; + private IMap<OldKey, OldValue> backing; private Function<OldValue, NewValue> transformer; - public TransformedValueMap(IMap<OldKey, OldValue> destMap, + public TransformedValueMap(IMap<OldKey, OldValue> backingMap, Function<OldValue, NewValue> transform) { - mapToTransform = destMap; + backing = backingMap; transformer = transform; } @Override public void clear() { - mapToTransform.clear(); + backing.clear(); } @Override public boolean containsKey(OldKey key) { - return mapToTransform.containsKey(key); + return backing.containsKey(key); } @Override @@ -44,62 +44,61 @@ final class TransformedValueMap<OldKey, OldValue, NewValue> @Override public void forEach(BiConsumer<OldKey, NewValue> action) { - mapToTransform.forEach((key, val) -> { - action.accept(key, transformer.apply(val)); + backing.forEach((key, value) -> { + action.accept(key, transformer.apply(value)); }); } @Override public void forEachKey(Consumer<OldKey> action) { - mapToTransform.forEachKey(action); + backing.forEachKey(action); } @Override public void forEachValue(Consumer<NewValue> action) { - mapToTransform.forEachValue((val) -> { - action.accept(transformer.apply(val)); + backing.forEachValue((value) -> { + action.accept(transformer.apply(value)); }); } @Override public NewValue get(OldKey key) { - return transformer.apply(mapToTransform.get(key)); + return transformer.apply(backing.get(key)); } @Override public int getSize() { - return mapToTransform.getSize(); + return backing.getSize(); } @Override public IList<OldKey> keyList() { - return mapToTransform.keyList(); + return backing.keyList(); } @Override - public <MappedValue> IMap<OldKey, MappedValue> mapValues( - Function<NewValue, MappedValue> transform) { + public <MappedValue> IMap<OldKey, MappedValue> + mapValues(Function<NewValue, MappedValue> transform) { return new TransformedValueMap<>(this, transform); } @Override - public NewValue put(OldKey key, NewValue val) { - throw new UnsupportedOperationException( - "Can't add items to transformed map"); + public NewValue put(OldKey key, NewValue value) { + throw new UnsupportedOperationException("Can't add items to transformed map"); } @Override public NewValue remove(OldKey key) { - return transformer.apply(mapToTransform.remove(key)); + return transformer.apply(backing.remove(key)); } @Override public String toString() { - return mapToTransform.toString(); + return backing.toString(); } @Override public IList<NewValue> valueList() { - return mapToTransform.valueList().map(transformer); + return backing.valueList().map(transformer); } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java index 865f4d6..b595946 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTree.java @@ -17,20 +17,20 @@ import bjc.utils.funcdata.IList; * The data type stored in the node. */ public class BinarySearchTree<T> { - /** + /* * The comparator for use in ordering items */ private Comparator<T> comparator; - /** + /* * The current count of elements in the tree */ private int elementCount; - /** + /* * The root element of the tree */ - private ITreePart<T> rootElement; + private ITreePart<T> root; /** * Create a new tree using the specified way to compare elements. @@ -56,10 +56,10 @@ public class BinarySearchTree<T> { public void addNode(T element) { elementCount++; - if (rootElement == null) { - rootElement = new BinarySearchTreeNode<>(element, null, null); + if (root == null) { + root = new BinarySearchTreeNode<>(element, null, null); } else { - rootElement.add(element, comparator); + root.add(element, comparator); } } @@ -74,25 +74,23 @@ public class BinarySearchTree<T> { * The distance from the pivot * @return Whether the adjusted pivot is with the list */ - private boolean adjustedPivotInBounds(IList<T> elements, int pivot, - int pivotAdjustment) { - return (pivot - pivotAdjustment) >= 0 - && (pivot + pivotAdjustment) < elements.getSize(); + private boolean adjustedPivotInBounds(IList<T> elements, int pivot, int pivotAdjustment) { + return (pivot - pivotAdjustment) >= 0 && (pivot + pivotAdjustment) < elements.getSize(); } /** - * Balance the tree, and remove soft-deleted nodes for free. Takes O(N) - * time, but also O(N) space. + * Balance the tree, and remove soft-deleted nodes for free. + * + * Takes O(N) time, but also O(N) space. */ public void balance() { IList<T> elements = new FunctionalList<>(); // Add each element to the list in sorted order - rootElement.forEach(TreeLinearizationMethod.INORDER, - element -> elements.add(element)); + root.forEach(TreeLinearizationMethod.INORDER, element -> elements.add(element)); // Clear the tree - rootElement = null; + root = null; // Set up the pivot and adjustment for readding elements int pivot = elements.getSize() / 2; @@ -100,19 +98,14 @@ public class BinarySearchTree<T> { // Add elements until there aren't any left while (adjustedPivotInBounds(elements, pivot, pivotAdjustment)) { - if (rootElement == null) { + if (root == null) { // Create a new root element - rootElement = new BinarySearchTreeNode<>( - elements.getByIndex(pivot), null, null); + root = new BinarySearchTreeNode<>(elements.getByIndex(pivot), null, null); } else { // Add the left and right elements in a balanced manner - rootElement.add( - elements.getByIndex(pivot + pivotAdjustment), - comparator); + root.add(elements.getByIndex(pivot + pivotAdjustment), comparator); - rootElement.add( - elements.getByIndex(pivot - pivotAdjustment), - comparator); + root.add(elements.getByIndex(pivot - pivotAdjustment), comparator); } // Increase the distance from the pivot @@ -121,18 +114,17 @@ public class BinarySearchTree<T> { // Add any trailing unbalanced elements if ((pivot - pivotAdjustment) >= 0) { - rootElement.add(elements.getByIndex(pivot - pivotAdjustment), - comparator); + root.add(elements.getByIndex(pivot - pivotAdjustment), comparator); } else if ((pivot + pivotAdjustment) < elements.getSize()) { - rootElement.add(elements.getByIndex(pivot + pivotAdjustment), - comparator); + root.add(elements.getByIndex(pivot + pivotAdjustment), comparator); } } /** - * Soft-delete a node from the tree. Soft-deleted nodes stay in the - * tree until trim()/balance() is invoked, and are not included in - * traversals/finds. + * Soft-delete a node from the tree. + * + * Soft-deleted nodes stay in the tree until trim()/balance() is invoked, and + * are not included in traversals/finds. * * @param element * The node to delete @@ -140,7 +132,7 @@ public class BinarySearchTree<T> { public void deleteNode(T element) { elementCount--; - rootElement.delete(element, comparator); + root.delete(element, comparator); } /** @@ -149,7 +141,7 @@ public class BinarySearchTree<T> { * @return The root of the tree. */ public ITreePart<T> getRoot() { - return rootElement; + return root; } /** @@ -160,7 +152,7 @@ public class BinarySearchTree<T> { * @return Whether or not the node is in the tree. */ public boolean isInTree(T element) { - return rootElement.contains(element, comparator); + return root.contains(element, comparator); } /** @@ -171,16 +163,14 @@ public class BinarySearchTree<T> { * @param traversalPredicate * The function to use until it fails */ - public void traverse(TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { + public void traverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { if (linearizationMethod == null) { - throw new NullPointerException( - "Linearization method must not be null"); + throw new NullPointerException("Linearization method must not be null"); } else if (traversalPredicate == null) { throw new NullPointerException("Predicate must not be nulls"); } - rootElement.forEach(linearizationMethod, traversalPredicate); + root.forEach(linearizationMethod, traversalPredicate); } /** @@ -196,9 +186,9 @@ public class BinarySearchTree<T> { }); // Clear the tree - rootElement = null; + root = null; // Add the nodes to the tree in the order they were inserted nodes.forEach(node -> addNode(node)); } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java index 8ceb554..d647742 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeLeaf.java @@ -34,27 +34,13 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { data = element; } - /* - * Can't add things to a leaf. (non-Javadoc) - * - * @see bjc.utils.data.bst.ITreePart#add(java.lang.Object, - * java.util.Comparator) - */ @Override public void add(T element, Comparator<T> comparator) { throw new IllegalArgumentException("Can't add to a leaf."); } - /* - * Just transform our data. (non-Javadoc) - * - * @see - * bjc.utils.data.bst.ITreePart#collapse(java.util.function.Function, - * java.util.function.BiFunction) - */ @Override - public <E> E collapse(Function<T, E> leafTransformer, - BiFunction<E, E, E> branchCollapser) { + public <E> E collapse(Function<T, E> leafTransformer, BiFunction<E, E, E> branchCollapser) { if (leafTransformer == null) { throw new NullPointerException("Transformer must not be null"); } @@ -62,33 +48,16 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { return leafTransformer.apply(data); } - /* - * Only check our data. (non-Javadoc) - * - * @see bjc.utils.data.bst.ITreePart#contains(java.lang.Object, - * java.util.Comparator) - */ @Override public boolean contains(T element, Comparator<T> comparator) { return this.data.equals(element); } - /* - * Just get the data (non-Javadoc) - * - * @see bjc.utils.data.bst.ITreePart#data() - */ @Override public T data() { return data; } - /* - * Just mark ourselves as "not here" (non-Javadoc) - * - * @see bjc.utils.data.bst.ITreePart#delete(java.lang.Object, - * java.util.Comparator) - */ @Override public void delete(T element, Comparator<T> comparator) { if (data.equals(element)) { @@ -96,13 +65,6 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { } } - /* - * Just walk our data and only succede if the walk does, because - * there's nowhere left to go. (non-Javadoc) - * - * @see bjc.utils.data.bst.ITreePart#directedWalk(bjc.utils.data.bst. - * DirectedWalkFunction) - */ @Override public boolean directedWalk(DirectedWalkFunction<T> treeWalker) { if (treeWalker == null) { @@ -121,16 +83,8 @@ public class BinarySearchTreeLeaf<T> implements ITreePart<T> { } } - /* - * Just check our data. (non-Javadoc) - * - * @see - * bjc.utils.data.bst.ITreePart#forEach(bjc.utils.data.bst.ITreePart. - * TreeLinearizationMethod, java.util.function.Predicate) - */ @Override - public boolean forEach(TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { + public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { if (traversalPredicate == null) { throw new NullPointerException("Predicate must not be null"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java index 9817f91..fa3add0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/BinarySearchTreeNode.java @@ -19,39 +19,33 @@ import java.util.function.Predicate; * The data type stored in the tree. */ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { - /** + /* * The left child of this node */ - private ITreePart<T> leftBranch; + private ITreePart<T> left; - /** + /* * The right child of this node */ - private ITreePart<T> rightBranch; + private ITreePart<T> right; /** * Create a new node with the specified data and children. * * @param element * The data to store in this node. - * @param left + * @param lft * The left child of this node. - * @param right + * @param rght * The right child of this node. */ - public BinarySearchTreeNode(T element, ITreePart<T> left, - ITreePart<T> right) { + public BinarySearchTreeNode(T element, ITreePart<T> lft, + ITreePart<T> rght) { super(element); - this.leftBranch = left; - this.rightBranch = right; + this.left = lft; + this.right = rght; } - /* - * Either adds it to the left/right, or undeletes itself. (non-Javadoc) - * - * @see bjc.utils.data.bst.TreeLeaf#add(java.lang.Object, - * java.util.Comparator) - */ @Override public void add(T element, Comparator<T> comparator) { if (comparator == null) { @@ -60,65 +54,57 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { switch (comparator.compare(data, element)) { case -1: - if (leftBranch == null) { - leftBranch = new BinarySearchTreeNode<>(element, null, - null); + if (left == null) { + left = new BinarySearchTreeNode<>(element, null, null); } else { - leftBranch.add(element, comparator); + left.add(element, comparator); } + break; case 0: if (isDeleted) { isDeleted = false; } else { - throw new IllegalArgumentException( - "Can't add duplicate values"); + throw new IllegalArgumentException("Can't add duplicate values"); } + break; case 1: - if (rightBranch == null) { - rightBranch = new BinarySearchTreeNode<>(element, null, - null); + if (right == null) { + right = new BinarySearchTreeNode<>(element, null, null); } else { - rightBranch.add(element, comparator); + right.add(element, comparator); } + break; default: - throw new IllegalStateException( - "Error: Comparator yielded invalid value"); + throw new IllegalStateException("Error: Comparator yielded invalid value"); } } @Override - public <E> E collapse(Function<T, E> nodeCollapser, - BiFunction<E, E, E> branchCollapser) { + public <E> E collapse(Function<T, E> nodeCollapser, BiFunction<E, E, E> branchCollapser) { if (nodeCollapser == null || branchCollapser == null) { throw new NullPointerException("Collapser must not be null"); } E collapsedNode = nodeCollapser.apply(data); - if (leftBranch != null) { - E collapsedLeftBranch = leftBranch.collapse(nodeCollapser, - branchCollapser); - if (rightBranch != null) { - E collapsedRightBranch = rightBranch - .collapse(nodeCollapser, branchCollapser); + if (left != null) { + E collapsedLeftBranch = left.collapse(nodeCollapser, branchCollapser); - E collapsedBranches = branchCollapser - .apply(collapsedLeftBranch, collapsedRightBranch); + if (right != null) { + E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); - return branchCollapser.apply(collapsedNode, - collapsedBranches); + E collapsedBranches = branchCollapser.apply(collapsedLeftBranch, collapsedRightBranch); + + return branchCollapser.apply(collapsedNode, collapsedBranches); } - return branchCollapser.apply(collapsedNode, - collapsedLeftBranch); + return branchCollapser.apply(collapsedNode, collapsedLeftBranch); } - if (rightBranch != null) { - E collapsedRightBranch = rightBranch.collapse(nodeCollapser, - branchCollapser); + if (right != null) { + E collapsedRightBranch = right.collapse(nodeCollapser, branchCollapser); - return branchCollapser.apply(collapsedNode, - collapsedRightBranch); + return branchCollapser.apply(collapsedNode, collapsedRightBranch); } return collapsedNode; @@ -153,12 +139,12 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { directedWalk(currentElement -> { switch (comparator.compare(data, element)) { case -1: - return leftBranch == null ? FAILURE : LEFT; + return left == null ? FAILURE : LEFT; case 0: isDeleted = true; return FAILURE; case 1: - return rightBranch == null ? FAILURE : RIGHT; + return right == null ? FAILURE : RIGHT; default: return FAILURE; } @@ -175,9 +161,9 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { case SUCCESS: return true; case LEFT: - return leftBranch.directedWalk(treeWalker); + return left.directedWalk(treeWalker); case RIGHT: - return rightBranch.directedWalk(treeWalker); + return right.directedWalk(treeWalker); case FAILURE: return false; default: @@ -186,25 +172,20 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } @Override - public boolean forEach(TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { + public boolean forEach(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { if (linearizationMethod == null) { - throw new NullPointerException( - "Linearization method must not be null"); + throw new NullPointerException("Linearization method must not be null"); } else if (traversalPredicate == null) { throw new NullPointerException("Predicate must not be null"); } switch (linearizationMethod) { case PREORDER: - return preorderTraverse(linearizationMethod, - traversalPredicate); + return preorderTraverse(linearizationMethod, traversalPredicate); case INORDER: - return inorderTraverse(linearizationMethod, - traversalPredicate); + return inorderTraverse(linearizationMethod, traversalPredicate); case POSTORDER: - return postorderTraverse(linearizationMethod, - traversalPredicate); + return postorderTraverse(linearizationMethod, traversalPredicate); default: throw new IllegalArgumentException( "Passed an incorrect TreeLinearizationMethod " @@ -212,10 +193,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } } - private boolean inorderTraverse( - TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { - + private boolean inorderTraverse( TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { return false; } @@ -224,24 +202,19 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return false; } - if (!traverseRightBranch(linearizationMethod, - traversalPredicate)) { + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) { return false; } return true; } - private boolean postorderTraverse( - TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { - + private boolean postorderTraverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { if (!traverseLeftBranch(linearizationMethod, traversalPredicate)) { return false; } - if (!traverseRightBranch(linearizationMethod, - traversalPredicate)) { + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) { return false; } @@ -253,10 +226,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { } - private boolean preorderTraverse( - TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { - + private boolean preorderTraverse(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { if (!traverseElement(traversalPredicate)) { return false; } @@ -265,8 +235,7 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { return false; } - if (!traverseRightBranch(linearizationMethod, - traversalPredicate)) { + if (!traverseRightBranch(linearizationMethod, traversalPredicate)) { return false; } @@ -275,37 +244,37 @@ public class BinarySearchTreeNode<T> extends BinarySearchTreeLeaf<T> { private boolean traverseElement(Predicate<T> traversalPredicate) { boolean nodeSuccesfullyTraversed; + if (isDeleted) { nodeSuccesfullyTraversed = true; } else { nodeSuccesfullyTraversed = traversalPredicate.test(data); } + return nodeSuccesfullyTraversed; } - private boolean traverseLeftBranch( - TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { + private boolean traverseLeftBranch(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { boolean leftSuccesfullyTraversed; - if (leftBranch == null) { + + if (left == null) { leftSuccesfullyTraversed = true; } else { - leftSuccesfullyTraversed = leftBranch - .forEach(linearizationMethod, traversalPredicate); + leftSuccesfullyTraversed = left.forEach(linearizationMethod, traversalPredicate); } + return leftSuccesfullyTraversed; } - private boolean traverseRightBranch( - TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate) { + private boolean traverseRightBranch(TreeLinearizationMethod linearizationMethod, Predicate<T> traversalPredicate) { boolean rightSuccesfullyTraversed; - if (rightBranch == null) { + + if (right == null) { rightSuccesfullyTraversed = true; } else { - rightSuccesfullyTraversed = rightBranch - .forEach(linearizationMethod, traversalPredicate); + rightSuccesfullyTraversed = right.forEach(linearizationMethod, traversalPredicate); } + return rightSuccesfullyTraversed; } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java index cbd7229..c574196 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/bst/ITreePart.java @@ -74,11 +74,11 @@ public interface ITreePart<T> { /** * Execute a directed walk through the tree. * - * @param treeWalker + * @param walker * The function to use to direct the walk through the tree. * @return Whether the directed walk finished successfully. */ - public boolean directedWalk(DirectedWalkFunction<T> treeWalker); + public boolean directedWalk(DirectedWalkFunction<T> walker); /** * Execute a provided function for each element of tree it succesfully @@ -86,11 +86,11 @@ public interface ITreePart<T> { * * @param linearizationMethod * The way to linearize the tree for executing - * @param traversalPredicate - * The function to apply to each element, where it returning + * @param predicate + * The predicate to apply to each element, where it returning * false terminates traversal early * @return Whether the traversal finished succesfully */ public boolean forEach(TreeLinearizationMethod linearizationMethod, - Predicate<T> traversalPredicate); + Predicate<T> predicate); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java index 10cfffe..9749d95 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcdata/theory/Functor.java @@ -27,10 +27,9 @@ public interface Functor<ContainedType> { * @return The passed in function converted to work over a particular * type of functors */ - public <ArgType, - ReturnType> Function<Functor<ArgType>, - Functor<ReturnType>> fmap( - Function<ArgType, ReturnType> func); + public <ArgType, ReturnType> + Function<Functor<ArgType>, Functor<ReturnType>> + fmap(Function<ArgType, ReturnType> func); /** * Retrieve the thing inside this functor diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java index 0a1efd5..eb3695e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CollectorUtils.java @@ -25,20 +25,17 @@ public class CollectorUtils { * The final type of the first collector * @param <FinalType2> * The final type of the second collector - * @param firstCollector + * @param first * The first collector to use - * @param secondCollector + * @param second * The second collector to use * @return A collector that functions as mentioned above */ - public static <InitialType, AuxType1, AuxType2, FinalType1, - FinalType2> Collector<InitialType, - IHolder<IPair<AuxType1, AuxType2>>, - IPair<FinalType1, FinalType2>> compoundCollect( - Collector<InitialType, AuxType1, - FinalType1> firstCollector, - Collector<InitialType, AuxType2, - FinalType2> secondCollector) { - return new CompoundCollector<>(firstCollector, secondCollector); + public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> + Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> + compoundCollect( + Collector<InitialType, AuxType1, FinalType1> first, + Collector<InitialType, AuxType2, FinalType2> second) { + return new CompoundCollector<>(first, second); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java index 257f005..de5fe85 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/CompoundCollector.java @@ -12,77 +12,66 @@ import bjc.utils.data.IPair; import bjc.utils.data.Identity; import bjc.utils.data.Pair; -final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, - FinalType2> implements - Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, - IPair<FinalType1, FinalType2>> { - private Set< - java.util.stream.Collector.Characteristics> characteristicSet; +final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, FinalType2> + implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> { - private Collector<InitialType, AuxType1, FinalType1> firstCollector; - private Collector<InitialType, AuxType2, - FinalType2> secondCollector; + private Set<java.util.stream.Collector.Characteristics> characteristicSet; + + private Collector<InitialType, AuxType1, FinalType1> first; + private Collector<InitialType, AuxType2, FinalType2> second; public CompoundCollector( - Collector<InitialType, AuxType1, FinalType1> firstCollector, - Collector<InitialType, AuxType2, FinalType2> secondCollector) { - this.firstCollector = firstCollector; - this.secondCollector = secondCollector; + Collector<InitialType, AuxType1, FinalType1> first, + Collector<InitialType, AuxType2, FinalType2> second) { + this.first = first; + this.second = second; - characteristicSet = firstCollector.characteristics(); - characteristicSet.addAll(secondCollector.characteristics()); + characteristicSet = first.characteristics(); + characteristicSet.addAll(second.characteristics()); } @Override - public BiConsumer<IHolder<IPair<AuxType1, AuxType2>>, - InitialType> accumulator() { - BiConsumer<AuxType1, InitialType> firstAccumulator = firstCollector - .accumulator(); - BiConsumer<AuxType2, - InitialType> secondAccumulator = secondCollector - .accumulator(); + public BiConsumer<IHolder<IPair<AuxType1, AuxType2>>, InitialType> accumulator() { + BiConsumer<AuxType1, InitialType> firstAccumulator = first.accumulator(); + BiConsumer<AuxType2, InitialType> secondAccumulator = second.accumulator(); return (state, value) -> { state.doWith((statePair) -> { - statePair.doWith((leftState, rightState) -> { - firstAccumulator.accept(leftState, value); - secondAccumulator.accept(rightState, value); + statePair.doWith((left, right) -> { + firstAccumulator.accept(left, value); + secondAccumulator.accept(right, value); }); }); }; } @Override - public Set< - java.util.stream.Collector.Characteristics> characteristics() { + public Set<java.util.stream.Collector.Characteristics> characteristics() { return characteristicSet; } @Override public BinaryOperator<IHolder<IPair<AuxType1, AuxType2>>> combiner() { - BinaryOperator<AuxType1> firstCombiner = firstCollector.combiner(); - BinaryOperator< - AuxType2> secondCombiner = secondCollector.combiner(); + BinaryOperator<AuxType1> firstCombiner = first.combiner(); + BinaryOperator<AuxType2> secondCombiner = second.combiner(); return (leftState, rightState) -> { return leftState.unwrap((leftPair) -> { return rightState.transform((rightPair) -> { - return leftPair.combine(rightPair, firstCombiner, - secondCombiner); + return leftPair.combine(rightPair, firstCombiner, secondCombiner); }); }); }; } @Override - public Function<IHolder<IPair<AuxType1, AuxType2>>, - IPair<FinalType1, FinalType2>> finisher() { + public Function<IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> finisher() { return (state) -> { return state.unwrap((pair) -> { - return pair.bind((leftVal, rightVal) -> { + return pair.bind((left, right) -> { return new Pair<>( - firstCollector.finisher().apply(leftVal), - secondCollector.finisher().apply(rightVal)); + first.finisher().apply(left), + second.finisher().apply(right)); }); }); }; @@ -90,8 +79,10 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, @Override public Supplier<IHolder<IPair<AuxType1, AuxType2>>> supplier() { - return () -> new Identity<>( - new Pair<>(firstCollector.supplier().get(), - secondCollector.supplier().get())); + return () -> { + return new Identity<>(new Pair<>( + first.supplier().get(), + second.supplier().get())); + }; } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java index 61b13ea..9be6080 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/EnumUtils.java @@ -18,7 +18,7 @@ public class EnumUtils { * * @param <E> * The type of the enum - * @param enumClass + * @param clasz * The enum class * @param nValues * The number of values to execute the action on @@ -27,9 +27,9 @@ public class EnumUtils { * @param rnd * The source of randomness to use */ - public static <E extends Enum<E>> void doForValues(Class<E> enumClass, + public static <E extends Enum<E>> void doForValues(Class<E> clasz, int nValues, Consumer<E> action, Random rnd) { - E[] enumValues = enumClass.getEnumConstants(); + E[] enumValues = clasz.getEnumConstants(); IList<E> valueList = new FunctionalList<>(enumValues); @@ -49,15 +49,15 @@ public class EnumUtils { * * @param <E> * The type of the enum - * @param enumClass + * @param clasz * The class of the enum * @param rnd * The random source to use * @return A random value from the specified enum */ - public static <E extends Enum<E>> E getRandomValue(Class<E> enumClass, + public static <E extends Enum<E>> E getRandomValue(Class<E> clasz, Random rnd) { - E[] enumValues = enumClass.getEnumConstants(); + E[] enumValues = clasz.getEnumConstants(); return new FunctionalList<>(enumValues).randItem(rnd::nextInt); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java index ea5c72e..6fc09ff 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FileUtils.java @@ -19,10 +19,10 @@ public class FileUtils { * * @param root * The directory to start the traversal at - * @param traversalPredicate + * @param predicate * The predicate to determine whether or not to traverse a * directory - * @param traversalAction + * @param action * The action to invoke upon each file in the directory. * Returning true means to continue the traversal, returning * false stops it @@ -33,10 +33,9 @@ public class FileUtils { * this with all the buttons and knobs from walkFileTree */ public static void traverseDirectory(Path root, - BiPredicate<Path, BasicFileAttributes> traversalPredicate, - BiPredicate<Path, BasicFileAttributes> traversalAction) + BiPredicate<Path, BasicFileAttributes> predicate, + BiPredicate<Path, BasicFileAttributes> action) throws IOException { - Files.walkFileTree(root, new FunctionalFileVisitor( - traversalPredicate, traversalAction)); + Files.walkFileTree(root, new FunctionalFileVisitor(predicate, action)); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java index 43603d6..679af52 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FuncUtils.java @@ -26,8 +26,7 @@ public class FuncUtils { * @return The function transformed into a unary function returning a * function */ - public static <A, B, C> Function<A, Function<B, C>> curry2( - BiFunction<A, B, C> func) { + public static <A, B, C> Function<A, Function<B, C>> curry2(BiFunction<A, B, C> func) { return (arg1) -> (arg2) -> { return func.apply(arg1, arg2); }; diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java index 2308d7c..cd833d9 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/FunctionalFileVisitor.java @@ -8,20 +8,20 @@ import java.nio.file.attribute.BasicFileAttributes; import java.util.function.BiPredicate; final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { - private BiPredicate<Path, BasicFileAttributes> traversalPredicate; - private BiPredicate<Path, BasicFileAttributes> traversalAction; + private BiPredicate<Path, BasicFileAttributes> predicate; + private BiPredicate<Path, BasicFileAttributes> action; public FunctionalFileVisitor( - BiPredicate<Path, BasicFileAttributes> traversalPredicate, - BiPredicate<Path, BasicFileAttributes> traversalAction) { - this.traversalPredicate = traversalPredicate; - this.traversalAction = traversalAction; + BiPredicate<Path, BasicFileAttributes> predicate, + BiPredicate<Path, BasicFileAttributes> action) { + this.predicate = predicate; + this.action = action; } @Override - public FileVisitResult preVisitDirectory(Path dir, - BasicFileAttributes attrs) throws IOException { - if (traversalPredicate.test(dir, attrs)) { + public FileVisitResult preVisitDirectory( + Path dir, BasicFileAttributes attrs) throws IOException { + if (predicate.test(dir, attrs)) { return FileVisitResult.CONTINUE; } @@ -31,10 +31,10 @@ final class FunctionalFileVisitor extends SimpleFileVisitor<Path> { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException { - if (traversalAction.test(file, attrs)) { + if (action.test(file, attrs)) { return FileVisitResult.CONTINUE; } return FileVisitResult.TERMINATE; } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java index 81781f6..229d271 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/GroupPartIteration.java @@ -17,10 +17,13 @@ import bjc.utils.funcdata.IList; */ final class GroupPartIteration<E> implements Consumer<E> { private IList<IList<E>> returnedList; + private IHolder<IList<E>> currentPartition; private IList<E> rejectedItems; + private IHolder<Integer> numberInCurrentPartition; private int numberPerPartition; + private Function<E, Integer> elementCounter; public GroupPartIteration(IList<IList<E>> returned, @@ -37,26 +40,24 @@ final class GroupPartIteration<E> implements Consumer<E> { @Override public void accept(E value) { - if (numberInCurrentPartition - .unwrap((number) -> number >= numberPerPartition)) { - returnedList.add( - currentPartition.unwrap((partition) -> partition)); + if (numberInCurrentPartition.unwrap((number) -> number >= numberPerPartition)) { + returnedList.add(currentPartition.unwrap((partition) -> partition)); - currentPartition - .transform((partition) -> new FunctionalList<>()); + currentPartition.transform((partition) -> new FunctionalList<>()); numberInCurrentPartition.transform((number) -> 0); } else { int currentElementCount = elementCounter.apply(value); - if (numberInCurrentPartition.unwrap((number) -> (number - + currentElementCount) >= numberPerPartition)) { + boolean shouldReject = numberInCurrentPartition.unwrap((number) -> { + return (number + currentElementCount) >= numberPerPartition; + }); + + if (shouldReject) { rejectedItems.add(value); } else { - currentPartition - .unwrap((partition) -> partition.add(value)); - numberInCurrentPartition.transform( - (number) -> number + currentElementCount); + currentPartition.unwrap((partition) -> partition.add(value)); + numberInCurrentPartition.transform((number) -> number + currentElementCount); } } } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java index 94571f5..4b17b41 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -47,8 +47,7 @@ public class ListUtils { * The seperator to use for seperating tokens * @return The collapsed string of tokens */ - public static String collapseTokens(IList<String> input, - String seperator) { + public static String collapseTokens(IList<String> input, String seperator) { if (input == null) { throw new NullPointerException("Input must not be null"); } else if (seperator == null) { @@ -60,12 +59,13 @@ public class ListUtils { } else if (input.getSize() == 1) { return input.first(); } else { - return input.reduceAux("", (currentString, state) -> { - return state + currentString + seperator; - }, (strang) -> { - return strang.substring(0, - strang.length() - seperator.length()); - }); + return input.reduceAux("", + (currentString, state) -> { + return state + currentString + seperator; + }, + (strang) -> { + return strang.substring(0, strang.length() - seperator.length()); + }); } } @@ -84,21 +84,20 @@ public class ListUtils { if (input == null) { throw new NullPointerException("Input must not be null"); } else if (operators == null) { - throw new NullPointerException( - "Set of operators must not be null"); + throw new NullPointerException("Set of operators must not be null"); } - IHolder<IList<String>> returnedList = new Identity<>(input); + IHolder<IList<String>> returned = new Identity<>(input); operators.forEach((operator) -> { - returnedList.transform((oldReturn) -> { - return oldReturn.flatMap((token) -> { + returned.transform((old) -> { + return old.flatMap((token) -> { return operator.merge(new TokenDeaffixer(token)); }); }); }); - return returnedList.unwrap((list) -> list); + return returned.unwrap((list) -> list); } /** @@ -108,7 +107,7 @@ public class ListUtils { * The type of items to select * @param list * The list to select from - * @param numberOfItems + * @param number * The number of items to selet * @param rng * A function that creates a random number from 0 to the @@ -117,26 +116,25 @@ public class ListUtils { * selected from the specified list without replacement */ - public static <E> IList<E> drawWithoutReplacement(IList<E> list, - int numberOfItems, Function<Integer, Integer> rng) { - IList<E> selectedItems = new FunctionalList<>( - new ArrayList<>(numberOfItems)); + public static <E> IList<E> drawWithoutReplacement( + IList<E> list, int number, Function<Integer, Integer> rng) { + IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); - int totalItems = list.getSize(); + int total = list.getSize(); list.forEachIndexed((index, element) -> { - int winningChance = numberOfItems - selectedItems.getSize(); + int winningChance = number - selected.getSize(); // n - m - int totalChance = totalItems - (index - 1); + int totalChance = total - (index - 1); // N - t // Probability of selecting the t+1'th element if (NumberUtils.isProbable(winningChance, totalChance, rng)) { - selectedItems.add(element); + selected.add(element); } }); - return selectedItems; + return selected; } /** @@ -146,7 +144,7 @@ public class ListUtils { * The type of items to select * @param list * The list to select from - * @param numberOfItems + * @param number * The number of items to selet * @param rng * A function that creates a random number from 0 to the @@ -155,15 +153,14 @@ public class ListUtils { * selected from the specified list */ public static <E> IList<E> drawWithReplacement(IList<E> list, - int numberOfItems, Function<Integer, Integer> rng) { - IList<E> selectedItems = new FunctionalList<>( - new ArrayList<>(numberOfItems)); + int number, Function<Integer, Integer> rng) { + IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); - for (int i = 0; i < numberOfItems; i++) { - selectedItems.add(list.randItem(rng)); + for (int i = 0; i < number; i++) { + selected.add(list.randItem(rng)); } - return selectedItems; + return selected; } /** @@ -175,23 +172,22 @@ public class ListUtils { * * @param input * The list to partition - * @param elementCounter + * @param counter * The function to determine the count for each element for - * @param numberPerPartition + * @param partitionSize * The number of elements to put in each partition * * @return A list partitioned according to the above rules */ - public static <E> IList<IList<E>> groupPartition(IList<E> input, - Function<E, Integer> elementCounter, int numberPerPartition) { + public static <E> IList<IList<E>> groupPartition( + IList<E> input, Function<E, Integer> counter, int partitionSize) { if (input == null) { throw new NullPointerException("Input list must not be null"); - } else if (elementCounter == null) { + } else if (counter == null) { throw new NullPointerException("Counter must not be null"); - } else if (numberPerPartition < 1 - || numberPerPartition > input.getSize()) { + } else if (partitionSize < 1 || partitionSize > input.getSize()) { throw new IllegalArgumentException( - "" + numberPerPartition + " is not a valid" + "" + partitionSize + " is not a valid" + " partition size. Must be between 1 and " + input.getSize()); } @@ -199,36 +195,36 @@ public class ListUtils { /* * List that holds our results */ - IList<IList<E>> returnedList = new FunctionalList<>(); + IList<IList<E>> returned = new FunctionalList<>(); /* * List that holds current partition */ - IHolder<IList<E>> currentPartition = new Identity<>( - new FunctionalList<>()); + IHolder<IList<E>> current = new Identity<>(new FunctionalList<>()); + /* * List that holds elements rejected during current pass */ - IList<E> rejectedElements = new FunctionalList<>(); + IList<E> rejected = new FunctionalList<>(); /* * The effective number of elements in the current partitition */ - IHolder<Integer> numberInCurrentPartition = new Identity<>(0); + IHolder<Integer> currentSize = new Identity<>(0); /* * Run up to a certain number of passes */ for (int numberOfIterations = 0; numberOfIterations < MAX_NTRIESPART - && !rejectedElements.isEmpty(); numberOfIterations++) { - input.forEach(new GroupPartIteration<>(returnedList, - currentPartition, rejectedElements, - numberInCurrentPartition, numberPerPartition, - elementCounter)); + && !rejected.isEmpty(); numberOfIterations++) { + input.forEach(new GroupPartIteration<>(returned, + current, rejected, + currentSize, partitionSize, + counter)); - if (rejectedElements.isEmpty()) { + if (rejected.isEmpty()) { // Nothing was rejected, so we're done - return returnedList; + return returned; } } @@ -237,11 +233,11 @@ public class ListUtils { + " iterations of partitioning) detected unpartitionable list " + input.toString() + "\nThe following elements were not partitioned: " - + rejectedElements.toString() + + rejected.toString() + "\nCurrent group in formation: " - + currentPartition.unwrap((vl) -> vl.toString()) + + current.unwrap((vl) -> vl.toString()) + "\nPreviously formed groups: " - + returnedList.toString()); + + returned.toString()); } /** @@ -255,13 +251,13 @@ public class ListUtils { */ @SafeVarargs public static <E> IList<E> mergeLists(IList<E>... lists) { - IList<E> returnedList = new FunctionalList<>(); + IList<E> returned = new FunctionalList<>(); for (IList<E> list : lists) { - list.forEach(returnedList::add); + list.forEach(returned::add); } - return returnedList; + return returned; } /** @@ -275,7 +271,7 @@ public class ListUtils { * The function to count elements with * @param size * The desired size of the list - * @param padSource + * @param padder * The function to get elements to pad with * @return The list, padded to the desired size * @throws IllegalArgumentException @@ -283,26 +279,26 @@ public class ListUtils { */ public static <E> IList<E> padList(IList<E> list, Function<E, Integer> counter, int size, - Supplier<E> padSource) { - IHolder<Integer> countHolder = new Identity<>(0); + Supplier<E> padder) { + IHolder<Integer> count = new Identity<>(0); - IList<E> ret = list.map((elm) -> { - countHolder.map((val) -> val + counter.apply(elm)); + IList<E> returned = list.map((elm) -> { + count.map((val) -> val + counter.apply(elm)); return elm; }); - if (countHolder.unwrap((val) -> val % size != 0)) { + if (count.unwrap((val) -> val % size != 0)) { // We need to pad - int needed = countHolder.unwrap((val) -> val % size); + int needed = count.unwrap((val) -> val % size); int threshold = 0; while (needed > 0 && threshold <= MAX_NTRIESPART) { - E val = padSource.get(); + E val = padder.get(); int count = counter.apply(val); if (count <= needed) { - ret.add(val); + returned.add(val); threshold = 0; @@ -319,7 +315,7 @@ public class ListUtils { } } - return ret; + return returned; } /** @@ -341,20 +337,19 @@ public class ListUtils { if (input == null) { throw new NullPointerException("Input must not be null"); } else if (operators == null) { - throw new NullPointerException( - "Set of operators must not be null"); + throw new NullPointerException("Set of operators must not be null"); } - IHolder<IList<String>> returnedList = new Identity<>(input); + IHolder<IList<String>> returned = new Identity<>(input); operators.forEach((operator) -> { - returnedList.transform((oldReturn) -> { + returned.transform((oldReturn) -> { return oldReturn.flatMap((token) -> { return operator.merge(new TokenSplitter(token)); }); }); }); - return returnedList.getValue(); + return returned.getValue(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java index 419c787..24c2014 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/NumberUtils.java @@ -26,8 +26,7 @@ public class NumberUtils { } else { int result = 1; - for (int currentSub = 0; currentSub < power + 1; - currentSub++) { + for (int currentSub = 0; currentSub < power + 1; currentSub++) { result *= value - currentSub; } @@ -38,16 +37,16 @@ public class NumberUtils { /** * Evaluates a linear probability distribution * - * @param topExp + * @param winning * The number of winning possibilities - * @param bottomExp + * @param total * The number of total possibilities * @param rng * The function to use to generate a random possibility * @return Whether or not a random possibility was a winning one */ - public static boolean isProbable(int topExp, int bottomExp, + public static boolean isProbable(int winning, int total, Function<Integer, Integer> rng) { - return rng.apply(bottomExp) < topExp; + return rng.apply(total) < winning; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java index 7573bfb..6770df2 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/StringUtils.java @@ -9,7 +9,6 @@ import java.util.Deque; * */ public class StringUtils { - /** * Checks if the given expression contains the specified operator in a * situation that indicates its use as an infix operator. @@ -21,12 +20,10 @@ public class StringUtils { * @return Whether or not the given expression contains the specified * operator as a infix operator */ - public static boolean containsInfixOperator(String expression, - String operator) { + public static boolean containsInfixOperator(String expression, String operator) { // Bit annoying to have to use a full class name, but what are you // going to do? - return org.apache.commons.lang3.StringUtils - .countMatches(expression, operator) == 1 + return org.apache.commons.lang3.StringUtils.countMatches(expression, operator) == 1 && !expression.equalsIgnoreCase(operator) && !expression.startsWith(operator); } @@ -85,8 +82,7 @@ public class StringUtils { * @return A string version of the deque, with allowance for an empty * deque */ - public static < - ContainedType> String printDeque(Deque<ContainedType> queue) { + public static <ContainedType> String printDeque(Deque<ContainedType> queue) { return queue.isEmpty() ? "(none)" : queue.toString(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java index 709538b..79f6e3b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/funcutils/TokenDeaffixer.java @@ -16,23 +16,19 @@ final class TokenDeaffixer @Override public IList<String> apply(String operatorName, String operatorRegex) { if (operatorName == null) { - throw new NullPointerException( - "Operator name must not be null"); + throw new NullPointerException("Operator name must not be null"); } else if (operatorRegex == null) { - throw new NullPointerException( - "Operator regex must not be null"); + throw new NullPointerException("Operator regex must not be null"); } if (StringUtils.containsOnly(token, operatorRegex)) { return new FunctionalList<>(token); } else if (token.startsWith(operatorName)) { - return new FunctionalList<>(operatorName, - token.split(operatorRegex)[1]); + return new FunctionalList<>(operatorName, token.split(operatorRegex)[1]); } else if (token.endsWith(operatorName)) { - return new FunctionalList<>(token.split(operatorRegex)[0], - operatorName); + return new FunctionalList<>(token.split(operatorRegex)[0], operatorName); } else { return new FunctionalList<>(token); } } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java index 4819ca2..2df820c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gen/WeightedRandom.java @@ -18,17 +18,17 @@ import bjc.utils.funcdata.IList; * The type of values that are randomly selected. */ public class WeightedRandom<E> { - /** + /* * The list of probabilities for each result */ private IList<Integer> probabilities; - /** + /* * The list of possible results to pick from */ private IList<E> results; - /** + /* * The source for any needed random numbers */ private Random source; @@ -75,27 +75,23 @@ public class WeightedRandom<E> { * @return A random value selected in a weighted fashion. */ public E generateValue() { - IHolder<Integer> randomValue = new Identity<>( - source.nextInt(totalChance)); - IHolder<E> currentResult = new Identity<>(); - IHolder<Boolean> valuePicked = new Identity<>(true); - - probabilities.forEachIndexed((itemIndex, itemProbability) -> { - if (valuePicked.unwrap(bool -> bool)) { - if (randomValue - .unwrap((number) -> number < itemProbability)) { - currentResult.transform( - (result) -> results.getByIndex(itemIndex)); - - valuePicked.transform((bool) -> false); + IHolder<Integer> value = new Identity<>(source.nextInt(totalChance)); + IHolder<E> current = new Identity<>(); + IHolder<Boolean> picked = new Identity<>(true); + + probabilities.forEachIndexed((index, probability) -> { + if (picked.unwrap(bool -> bool)) { + if (value.unwrap((number) -> number < probability)) { + current.transform((result) -> results.getByIndex(index)); + + picked.transform((bool) -> false); } else { - randomValue.transform( - (number) -> number - itemProbability); + value.transform((number) -> number - probability); } } }); - return currentResult.unwrap((result) -> result); + return current.unwrap((result) -> result); } /** diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java index ff9103e..2f6d91a 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/AdjacencyMap.java @@ -37,22 +37,22 @@ public class AdjacencyMap<T> { } // Create the adjacency map - AdjacencyMap<Integer> adjacencyMap; + AdjacencyMap<Integer> adjacency; - try (Scanner inputSource = new Scanner(stream)) { - inputSource.useDelimiter("\n"); + try (Scanner input = new Scanner(stream)) { + input.useDelimiter("\n"); - int numVertices; + int vertexCount; - String possibleVertices = inputSource.next(); + String possible = input.next(); try { // First, read in number of vertices - numVertices = Integer.parseInt(possibleVertices); + vertexCount = Integer.parseInt(possible); } catch (NumberFormatException nfex) { InputMismatchException imex = new InputMismatchException( "The first line must contain the number of vertices. " - + possibleVertices + + possible + " is not a valid number"); imex.initCause(nfex); @@ -60,45 +60,44 @@ public class AdjacencyMap<T> { throw imex; } - if (numVertices <= 0) { + if (vertexCount <= 0) { throw new InputMismatchException( "The number of vertices must be greater than 0"); } IList<Integer> vertices = new FunctionalList<>(); - FuncUtils.doTimes(numVertices, - (vertexNo) -> vertices.add(vertexNo)); + FuncUtils.doTimes(vertexCount, (vertexNo) -> vertices.add(vertexNo)); - adjacencyMap = new AdjacencyMap<>(vertices); + adjacency = new AdjacencyMap<>(vertices); IHolder<Integer> row = new Identity<>(0); - inputSource.forEachRemaining((strang) -> { - readRow(adjacencyMap, numVertices, row, strang); + input.forEachRemaining((strang) -> { + readRow(adjacency, vertexCount, row, strang); }); } - return adjacencyMap; + return adjacency; } - private static void readRow(AdjacencyMap<Integer> adjacencyMap, - int numVertices, IHolder<Integer> row, String strang) { + private static void readRow(AdjacencyMap<Integer> adjacency, + int vertexCount, IHolder<Integer> row, String strang) { String[] parts = strang.split(" "); - if (parts.length != numVertices) { + if (parts.length != vertexCount) { throw new InputMismatchException( - "Must specify a weight for all " + numVertices + "Must specify a weight for all " + vertexCount + " vertices"); } int column = 0; for (String part : parts) { - int columnWeight; + int weight; try { - columnWeight = Integer.parseInt(part); + weight = Integer.parseInt(part); } catch (NumberFormatException nfex) { InputMismatchException imex = new InputMismatchException( "" + part + " is not a valid weight."); @@ -108,7 +107,7 @@ public class AdjacencyMap<T> { throw imex; } - adjacencyMap.setWeight(row.getValue(), column, columnWeight); + adjacency.setWeight(row.getValue(), column, weight); column++; } @@ -119,7 +118,7 @@ public class AdjacencyMap<T> { /** * The backing storage of the map */ - private IMap<T, IMap<T, Integer>> adjacencyMap = new FunctionalMap<>(); + private IMap<T, IMap<T, Integer>> adjacency = new FunctionalMap<>(); /** * Create a new map from a set of vertices @@ -133,13 +132,13 @@ public class AdjacencyMap<T> { } vertices.forEach(vertex -> { - IMap<T, Integer> vertexRow = new FunctionalMap<>(); + IMap<T, Integer> row = new FunctionalMap<>(); - vertices.forEach(targetVertex -> { - vertexRow.put(targetVertex, 0); + vertices.forEach(target -> { + row.put(target 0); }); - adjacencyMap.put(vertex, vertexRow); + adjacency.put(vertex, row); }); } @@ -151,9 +150,9 @@ public class AdjacencyMap<T> { public boolean isDirected() { IHolder<Boolean> result = new Identity<>(true); - adjacencyMap.forEach((key, value) -> { - value.forEach((targetKey, targetValue) -> { - int inverseValue = adjacencyMap.get(targetKey).get(key); + adjacency.forEach((sourceKey, sourceValue) -> { + sourceValue.forEach((targetKey, targetValue) -> { + int inverseValue = adjacency.get(targetKey).get(sourceKey); if (targetValue != inverseValue) { result.replace(false); @@ -167,31 +166,31 @@ public class AdjacencyMap<T> { /** * Set the weight of an edge * - * @param sourceVertex + * @param source * The source node of the edge - * @param targetVertex + * @param target * The target node of the edge - * @param edgeWeight + * @param weight * The weight of the edge */ - public void setWeight(T sourceVertex, T targetVertex, int edgeWeight) { - if (sourceVertex == null) { + public void setWeight(T source, T target int weight) { + if (source == null) { throw new NullPointerException( "Source vertex must not be null"); - } else if (targetVertex == null) { + } else if (target== null) { throw new NullPointerException( "Target vertex must not be null"); } - if (!adjacencyMap.containsKey(sourceVertex)) { + if (!adjacency.containsKey(source)) { throw new IllegalArgumentException("Source vertex " - + sourceVertex + " isn't present in map"); - } else if (!adjacencyMap.containsKey(targetVertex)) { + + source + " isn't present in map"); + } else if (!adjacency.containsKey(target) { throw new IllegalArgumentException("Target vertex " - + targetVertex + " isn't present in map"); + + target+ " isn't present in map"); } - adjacencyMap.get(sourceVertex).put(targetVertex, edgeWeight); + adjacency.get(source).put(target weight); } /** @@ -200,33 +199,33 @@ public class AdjacencyMap<T> { * @return The new representation of this graph */ public Graph<T> toGraph() { - Graph<T> returnedGraph = new Graph<>(); + Graph<T> ret = new Graph<>(); - adjacencyMap.forEach((key, value) -> { - value.forEach((targetKey, targetValue) -> { - returnedGraph.addEdge(key, targetKey, targetValue, true); + adjacency.forEach((sourceKey, sourceValue) -> { + sourceValue.forEach((targetKey, targetValue) -> { + ret.addEdge(sourceKey, targetKey, targetValue, true); }); }); - return returnedGraph; + return ret; } /** * Convert an adjacency map back into a stream * - * @param outputSink + * @param sink * The stream to convert to */ - public void toStream(OutputStream outputSink) { - if (outputSink == null) { + public void toStream(OutputStream sink) { + if (sink == null) { throw new NullPointerException( "Output source must not be null"); } - PrintStream outputPrinter = new PrintStream(outputSink); + PrintStream outputPrinter = new PrintStream(sink); - adjacencyMap.forEach((key, value) -> { - value.forEach((targetKey, targetValue) -> { + adjacency.forEach((sourceKey, sourceValue) -> { + sourceValue.forEach((targetKey, targetValue) -> { outputPrinter.printf("%d", targetValue); }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java index fa34083..2ad4132 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Edge.java @@ -9,12 +9,12 @@ package bjc.utils.graph; * The type of the nodes in the graph */ public class Edge<T> { - /** + /* * The distance from initial to terminal node */ private final int distance; - /** + /* * The initial and terminal nodes of this edge */ private final T source, target; @@ -22,32 +22,27 @@ public class Edge<T> { /** * Create a new edge with set parameters * - * @param initialNode + * @param initial * The initial node of the edge - * @param terminalNode + * @param terminal * The terminal node of the edge * @param distance * The distance between initial and terminal edge */ - public Edge(T initialNode, T terminalNode, int distance) { - if (initialNode == null) { + public Edge(T initial, T terminal, int distance) { + if (initial == null) { throw new NullPointerException( "Initial node must not be null"); - } else if (terminalNode == null) { + } else if (terminal == null) { throw new NullPointerException( "Terminal node must not be null"); } - this.source = initialNode; - this.target = terminalNode; + this.source = initial; + this.target = terminal; this.distance = distance; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#equals(java.lang.Object) - */ @Override public boolean equals(Object obj) { if (this == obj) { @@ -57,7 +52,6 @@ public class Edge<T> { } else if (getClass() != obj.getClass()) { return false; } else { - Edge<?> other = (Edge<?>) obj; if (distance != other.distance) { @@ -108,20 +102,18 @@ public class Edge<T> { return target; } - /* - * (non-Javadoc) - * - * @see java.lang.Object#hashCode() - */ @Override public int hashCode() { final int prime = 31; + int result = 1; + result = prime * result + distance; result = prime * result + ((source == null) ? 0 : source.hashCode()); result = prime * result + ((target == null) ? 0 : target.hashCode()); + return result; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java index 68d0ef1..66fe580 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java +++ b/BJC-Utils2/src/main/java/bjc/utils/graph/Graph.java @@ -49,55 +49,55 @@ public class Graph<T> { /** * The backing representation of the graph */ - private final IMap<T, IMap<T, Integer>> backingGraph; + private final IMap<T, IMap<T, Integer>> backing; /** * Create a new graph */ public Graph() { - backingGraph = new FunctionalMap<>(); + backing = new FunctionalMap<>(); } /** * Add a edge to the graph * - * @param sourceVertex + * @param source * The source vertex for this edge - * @param targetVertex + * @param target * The target vertex for this edge * @param distance * The distance from the source vertex to the target vertex * @param directed * Whether or not */ - public void addEdge(T sourceVertex, T targetVertex, int distance, + public void addEdge(T source, T target, int distance, boolean directed) { // Can't add edges with a null source or target - if (sourceVertex == null) { + if (source == null) { throw new NullPointerException( "The source vertex cannot be null"); - } else if (targetVertex == null) { + } else if (target == null) { throw new NullPointerException( "The target vertex cannot be null"); } // Initialize adjacency list for vertices if necessary - if (!backingGraph.containsKey(sourceVertex)) { - backingGraph.put(sourceVertex, + if (!backing.containsKey(source)) { + backing.put(source, new FunctionalMap<T, Integer>()); } // Add the edge to the graph - backingGraph.get(sourceVertex).put(targetVertex, distance); + backing.get(source).put(target, distance); // Handle possible directed edges if (!directed) { - if (!backingGraph.containsKey(targetVertex)) { - backingGraph.put(targetVertex, + if (!backing.containsKey(target)) { + backing.put(target, new FunctionalMap<T, Integer>()); } - backingGraph.get(targetVertex).put(sourceVertex, distance); + backing.get(target).put(source, distance); } } @@ -105,25 +105,25 @@ public class Graph<T> { * Execute an action for all edges of a specific vertex matching * conditions * - * @param sourceVertex + * @param source * The vertex to test edges for - * @param edgeMatcher + * @param matcher * The conditions an edge must match - * @param edgeAction + * @param action * The action to execute for matching edges */ - public void forAllEdgesMatchingAt(T sourceVertex, - BiPredicate<T, Integer> edgeMatcher, - BiConsumer<T, Integer> edgeAction) { - if (edgeMatcher == null) { + public void forAllEdgesMatchingAt(T source, + BiPredicate<T, Integer> matcher, + BiConsumer<T, Integer> action) { + if (matcher == null) { throw new NullPointerException("Matcher must not be null"); - } else if (edgeAction == null) { + } else if (action == null) { throw new NullPointerException("Action must not be null"); } - getEdges(sourceVertex).forEach((targetVertex, vertexWeight) -> { - if (edgeMatcher.test(targetVertex, vertexWeight)) { - edgeAction.accept(targetVertex, vertexWeight); + getEdges(source).forEach((target, weight) -> { + if (matcher.test(target, weight)) { + action.accept(target, weight); } }); } @@ -139,12 +139,12 @@ public class Graph<T> { // Can't find edges for a null source if (source == null) { throw new NullPointerException("The source cannot be null."); - } else if (!backingGraph.containsKey(source)) { + } else if (!backing.containsKey(source)) { throw new IllegalArgumentException( "Vertex " + source + " is not in graph"); } - return backingGraph.get(source); + return backing.get(source); } /** @@ -153,67 +153,65 @@ public class Graph<T> { * @return The initial vertex of the graph */ public T getInitial() { - return backingGraph.keyList().first(); + return backing.keyList().first(); } /** - * Uses Prim's algorothm to calculate a MST for the graph. If the graph - * is non-connected, this will lead to unpredictable results. + * Uses Prim's algorothm to calculate a MST for the graph. + * + * If the graph is non-connected, this will lead to unpredictable results. * * @return a list of edges that constitute the MST */ public List<Edge<T>> getMinimumSpanningTree() { // Set of all of the currently available edges - Queue<Edge<T>> availableEdges = new PriorityQueue<>(10, - (leftEdge, rightEdge) -> leftEdge.getDistance() - - rightEdge.getDistance()); + Queue<Edge<T>> available = new PriorityQueue<>(10, + (left, right) -> left.getDistance() - right.getDistance()); // The MST of the graph - List<Edge<T>> minimumEdges = new ArrayList<>(); + List<Edge<T>> minimums = new ArrayList<>(); // The set of all of the visited vertices. - Set<T> visitedVertexes = new HashSet<>(); + Set<T> visited = new HashSet<>(); // Start at the initial vertex and visit it - IHolder<T> sourceVertex = new Identity<>(getInitial()); + IHolder<T> source = new Identity<>(getInitial()); - visitedVertexes.add(sourceVertex.getValue()); + visited.add(source.getValue()); // Make sure we visit all the nodes - while (visitedVertexes.size() != getVertexCount()) { + while (visited.size() != getVertexCount()) { // Grab all edges adjacent to the provided edge - forAllEdgesMatchingAt(sourceVertex.getValue(), - (targetVertex, vertexWeight) -> { - return !visitedVertexes.contains(targetVertex); - }, (targetVertex, vertexWeight) -> { - availableEdges.add(new Edge<>( - sourceVertex.unwrap(vertex -> vertex), - targetVertex, vertexWeight)); + forAllEdgesMatchingAt(source.getValue(), + (target, weight) -> { + return !visited.contains(target); + }, (target, weight) -> { + available.add(new Edge<>( + source.unwrap(vertex -> vertex), + target, weight)); }); // Get the edge with the minimum distance - IHolder<Edge<T>> minimumEdge = new Identity<>( - availableEdges.poll()); + IHolder<Edge<T>> minimum = new Identity<>(available.poll()); // Only consider edges where we haven't visited the target of // the edge - while (visitedVertexes.contains(minimumEdge.getValue())) { - minimumEdge.transform((edge) -> availableEdges.poll()); + while (visited.contains(minimum.getValue())) { + minimum.transform((edge) -> available.poll()); } // Add it to our MST - minimumEdges.add(minimumEdge.getValue()); + minimums.add(minimum.getValue()); // Advance to the next node - sourceVertex.transform((vertex) -> minimumEdge - .unwrap(edge -> edge.getTarget())); + source.transform((vertex) -> minimum.unwrap(edge -> edge.getTarget())); // Visit this node - visitedVertexes.add(sourceVertex.getValue()); + visited.add(source.getValue()); } - return minimumEdges; + return minimums; } /** @@ -222,7 +220,7 @@ public class Graph<T> { * @return A count of the vertices in this graph */ public int getVertexCount() { - return backingGraph.getSize(); + return backing.getSize(); } /** @@ -231,39 +229,39 @@ public class Graph<T> { * @return A unmodifiable set of all the vertices in the graph. */ public IList<T> getVertices() { - return backingGraph.keyList(); + return backing.keyList(); } /** * Remove the edge starting at the source and ending at the target * - * @param sourceVertex + * @param source * The source vertex for the edge - * @param targetVertex + * @param target * The target vertex for the edge */ - public void removeEdge(T sourceVertex, T targetVertex) { + public void removeEdge(T source, T target) { // Can't remove things w/ null vertices - if (sourceVertex == null) { + if (source == null) { throw new NullPointerException( "The source vertex cannot be null"); - } else if (targetVertex == null) { + } else if (target == null) { throw new NullPointerException( "The target vertex cannot be null"); } // Can't remove if one vertice doesn't exists - if (!backingGraph.containsKey(sourceVertex)) { + if (!backing.containsKey(source)) { throw new NoSuchElementException( - "vertex " + sourceVertex + " does not exist."); + "vertex " + source + " does not exist."); } - if (!backingGraph.containsKey(targetVertex)) { + if (!backing.containsKey(target)) { throw new NoSuchElementException( - "vertex " + targetVertex + " does not exist."); + "vertex " + target + " does not exist."); } - backingGraph.get(sourceVertex).remove(targetVertex); + backing.get(source).remove(target); // Uncomment this to turn the graph undirected // graph.get(target).remove(source); @@ -275,15 +273,15 @@ public class Graph<T> { * @return A adjacency map representing this graph */ public AdjacencyMap<T> toAdjacencyMap() { - AdjacencyMap<T> adjacencyMap = new AdjacencyMap<>( - backingGraph.keyList()); + AdjacencyMap<T> adjacency = new AdjacencyMap<>( + backing.keyList()); - backingGraph.forEach((key, value) -> { - value.forEach((targetKey, targetValue) -> { - adjacencyMap.setWeight(key, targetKey, targetValue); + backing.forEach((sourceKey, sourceValue) -> { + sourceValue.forEach((targetKey, targetValue) -> { + adjacency.setWeight(sourceKey, targetKey, targetValue); }); }); - return adjacencyMap; + return adjacency; } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java index 77e518e..68c4962 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleDialogs.java @@ -70,7 +70,6 @@ public class SimpleDialogs { @SuppressWarnings("unchecked") public static <E> E getChoice(Frame parent, String title, String question, E... choices) { - if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { @@ -79,8 +78,8 @@ public class SimpleDialogs { throw new NullPointerException("Question must not be null"); } - JDialog mainDialog = new JDialog(parent, title, true); - mainDialog.setLayout(new VLayout(2)); + JDialog chooser = new JDialog(parent, title, true); + chooser.setLayout(new VLayout(2)); JPanel questionPane = new JPanel(); @@ -95,17 +94,17 @@ public class SimpleDialogs { JButton okButton = new JButton("Ok"); JButton cancelButton = new JButton("Cancel"); - okButton.addActionListener((event) -> mainDialog.dispose()); - cancelButton.addActionListener((event) -> mainDialog.dispose()); + okButton.addActionListener((event) -> chooser.dispose()); + cancelButton.addActionListener((event) -> chooser.dispose()); buttonPane.add(cancelButton); buttonPane.add(okButton); - mainDialog.add(questionPane); - mainDialog.add(buttonPane); + chooser.add(questionPane); + chooser.add(buttonPane); - mainDialog.pack(); - mainDialog.setVisible(true); + chooser.pack(); + chooser.setVisible(true); return (E) questionChoices.getSelectedItem(); } @@ -172,30 +171,30 @@ public class SimpleDialogs { * The title for dialogs. * @param prompt * The prompt to tell the user what to enter. - * @param inputValidator + * @param validator * A predicate to determine if a input is valid. - * @param inputTransformer + * @param transformer * The function to transform the string into a value. * @return The value parsed from a string. */ public static <E> E getValue(Component parent, String title, - String prompt, Predicate<String> inputValidator, - Function<String, E> inputTransformer) { - if (inputValidator == null) { + String prompt, Predicate<String> validator, + Function<String, E> transformer) { + if (validator == null) { throw new NullPointerException("Validator must not be null"); - } else if (inputTransformer == null) { + } else if (transformer == null) { throw new NullPointerException("Transformer must not be null"); } - String inputString = getString(parent, title, prompt); + String input = getString(parent, title, prompt); - while (!inputValidator.test(inputString)) { + while (!validator.test(input)) { showError(parent, "I/O Error", "Please enter a valid value"); - inputString = getString(parent, title, prompt); + input = getString(parent, title, prompt); } - return inputTransformer.apply(inputString); + return transformer.apply(input); } /** @@ -235,10 +234,10 @@ public class SimpleDialogs { throw new NullPointerException("Question must not be null"); } - int dialogResult = JOptionPane.showConfirmDialog(parent, question, + int result = JOptionPane.showConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); - return (dialogResult == JOptionPane.YES_OPTION ? true : false); + return (result == JOptionPane.YES_OPTION ? true : false); } /** @@ -248,21 +247,21 @@ public class SimpleDialogs { * The parent component for dialogs. * @param title * The title for dialogs. - * @param errorMessage + * @param message * The error to show the user. */ public static void showError(Component parent, String title, - String errorMessage) { + String message) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { throw new NullPointerException("Title must not be null"); - } else if (errorMessage == null) { + } else if (message == null) { throw new NullPointerException( "Error message must not be null"); } - JOptionPane.showMessageDialog(parent, errorMessage, title, + JOptionPane.showMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); } @@ -289,4 +288,4 @@ public class SimpleDialogs { JOptionPane.showMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE); } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java index 010de5f..ae77e41 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleFileChooser.java @@ -147,9 +147,9 @@ public class SimpleFileChooser { "File chooser must not be null"); } - int dialogResult = files.showSaveDialog(parent); + int result = files.showSaveDialog(parent); - if (dialogResult != JFileChooser.APPROVE_OPTION) { + if (result != JFileChooser.APPROVE_OPTION) { throw new FileNotChosenException(); } } @@ -163,9 +163,9 @@ public class SimpleFileChooser { "File chooser must not be null"); } - int dialogResult = files.showSaveDialog(parent); + int result = files.showSaveDialog(parent); - if (dialogResult != JFileChooser.APPROVE_OPTION) { + if (result != JFileChooser.APPROVE_OPTION) { throw new FileNotChosenException(); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java index d38cadf..0152870 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleInternalDialogs.java @@ -7,8 +7,9 @@ import java.util.function.Predicate; import javax.swing.JOptionPane; /** - * Utility class for getting simple input from the user. Modified to work - * with JDesktopPanes + * Utility class for getting simple input from the user. + * + * Modified to work with JDesktopPanes * * @author ben * @@ -106,30 +107,30 @@ public class SimpleInternalDialogs { * The title for dialogs. * @param prompt * The prompt to tell the user what to enter. - * @param inputValidator + * @param validator * A predicate to determine if a input is valid. - * @param inputTransformer + * @param transformer * The function to transform the string into a value. * @return The value parsed from a string. */ public static <E> E getValue(Component parent, String title, - String prompt, Predicate<String> inputValidator, - Function<String, E> inputTransformer) { - if (inputValidator == null) { + String prompt, Predicate<String> validator, + Function<String, E> transformer) { + if (validator == null) { throw new NullPointerException("Validator must not be null"); - } else if (inputTransformer == null) { + } else if (transformer == null) { throw new NullPointerException("Transformer must not be null"); } - String inputString = getString(parent, title, prompt); + String strang = getString(parent, title, prompt); - while (!inputValidator.test(inputString)) { + while (!validator.test(strang)) { showError(parent, "I/O Error", "Please enter a valid value"); - inputString = getString(parent, title, prompt); + strang = getString(parent, title, prompt); } - return inputTransformer.apply(inputString); + return transformer.apply(strang); } /** @@ -169,10 +170,10 @@ public class SimpleInternalDialogs { throw new NullPointerException("Question must not be null"); } - int dialogResult = JOptionPane.showInternalConfirmDialog(parent, + int result = JOptionPane.showInternalConfirmDialog(parent, question, title, JOptionPane.YES_NO_OPTION); - return (dialogResult == JOptionPane.YES_OPTION ? true : false); + return (result == JOptionPane.YES_OPTION ? true : false); } /** @@ -182,21 +183,21 @@ public class SimpleInternalDialogs { * The parent component for dialogs. * @param title * The title for dialogs. - * @param errorMessage + * @param message * The error to show the user. */ public static void showError(Component parent, String title, - String errorMessage) { + String message) { if (parent == null) { throw new NullPointerException("Parent must not be null"); } else if (title == null) { throw new NullPointerException("Title must not be null"); - } else if (errorMessage == null) { + } else if (message == null) { throw new NullPointerException( "Error message must not be null"); } - JOptionPane.showInternalMessageDialog(parent, errorMessage, title, + JOptionPane.showInternalMessageDialog(parent, message, title, JOptionPane.ERROR_MESSAGE); } @@ -223,4 +224,4 @@ public class SimpleInternalDialogs { JOptionPane.showInternalMessageDialog(parent, title, message, JOptionPane.INFORMATION_MESSAGE); } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java index 4db5027..136c662 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/SimpleJList.java @@ -17,16 +17,16 @@ public class SimpleJList { * @param <E> * The type of data in the JList * - * @param listSource + * @param source * The list to populate the JList with. * @return A JList populated with the elements from ls. */ - public static <E> JList<E> buildFromList(Iterable<E> listSource) { - if (listSource == null) { + public static <E> JList<E> buildFromList(Iterable<E> source) { + if (source == null) { throw new NullPointerException("Source must not be null"); } - return new JList<>(buildModel(listSource)); + return new JList<>(buildModel(source)); } /** @@ -35,18 +35,18 @@ public class SimpleJList { * @param <E> * The type of data in the list model * - * @param listSource + * @param source * The list to fill the list model from. * @return A list model populated with the elements from ls. */ - public static <E> ListModel<E> buildModel(Iterable<E> listSource) { - if (listSource == null) { + public static <E> ListModel<E> buildModel(Iterable<E> source) { + if (source == null) { throw new NullPointerException("Source must not be null"); } DefaultListModel<E> defaultModel = new DefaultListModel<>(); - listSource.forEach(defaultModel::addElement); + source.forEach(defaultModel::addElement); return defaultModel; } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java b/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java index 6080462..6ff716b 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/TextAreaOutputStream.java @@ -6,11 +6,12 @@ import java.io.OutputStream; import javax.swing.JTextArea; /** + * An output stream that prints to a JTextArea + * * @author epr * @author Levente S\u00e1ntha (lsantha@users.sourceforge.net) */ public class TextAreaOutputStream extends OutputStream { - private JTextArea textArea; /** @@ -26,8 +27,9 @@ public class TextAreaOutputStream extends OutputStream { @Override public void write(int b) throws IOException { textArea.append("" + (char) b); + if (b == '\n') { textArea.repaint(); } } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java index 79ba4be..280c5d8 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/awt/SimpleFileDialog.java @@ -48,23 +48,23 @@ public class SimpleFileDialog { throw new NullPointerException("Title must not be null"); } - FileDialog fileDialog = new FileDialog(parent, title, + FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); if (extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); - fileDialog.setFilenameFilter(filter); + chooser.setFilenameFilter(filter); } - fileDialog.setVisible(true); + chooser.setVisible(true); - while (fileDialog.getFile() == null) { + while (chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); - fileDialog.setVisible(true); + chooser.setVisible(true); } - return fileDialog.getFiles()[0]; + return chooser.getFiles()[0]; } /** @@ -86,24 +86,24 @@ public class SimpleFileDialog { throw new NullPointerException("Title must not be null"); } - FileDialog fileDialog = new FileDialog(parent, title, + FileDialog chooser = new FileDialog(parent, title, FileDialog.LOAD); if (extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); - fileDialog.setFilenameFilter(filter); + chooser.setFilenameFilter(filter); } - fileDialog.setMultipleMode(true); - fileDialog.setVisible(true); + chooser.setMultipleMode(true); + chooser.setVisible(true); - while (fileDialog.getFile() == null) { + while (chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to open."); - fileDialog.setVisible(true); + chooser.setVisible(true); } - return fileDialog.getFiles(); + return chooser.getFiles(); } /** @@ -138,22 +138,22 @@ public class SimpleFileDialog { throw new NullPointerException("Title must not be null"); } - FileDialog fileDialog = new FileDialog(parent, title, + FileDialog chooser = new FileDialog(parent, title, FileDialog.SAVE); if (extensions != null) { FilenameFilter filter = new ExtensionFileFilter(extensions); - fileDialog.setFilenameFilter(filter); + chooser.setFilenameFilter(filter); } - fileDialog.setVisible(true); + chooser.setVisible(true); - while (fileDialog.getFile() == null) { + while (chooser.getFile() == null) { SimpleDialogs.showError(parent, "File I/O Error", "Please choose a file to save to."); - fileDialog.setVisible(true); + chooser.setVisible(true); } - return fileDialog.getFiles()[0]; + return chooser.getFiles()[0]; } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java index c98eea3..895faa6 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java @@ -27,15 +27,15 @@ public class DropdownListPanel extends JPanel { * * @param <T> * The type of items in the dropdown list - * @param itemType + * @param type * The label of the type of items in the list - * @param listModel + * @param model * The model to put items into * @param choices * The items to choose from */ - public <T> DropdownListPanel(String itemType, - DefaultListModel<T> listModel, IList<T> choices) { + public <T> DropdownListPanel(String type, + DefaultListModel<T> model, IList<T> choices) { setLayout(new AutosizeLayout()); JPanel itemInputPanel = new JPanel(); @@ -47,23 +47,23 @@ public class DropdownListPanel extends JPanel { JComboBox<T> addItemBox = new JComboBox<>(); choices.forEach(addItemBox::addItem); - JButton addItemButton = new JButton("Add " + itemType); + JButton addItemButton = new JButton("Add " + type); addItemPanel.add(addItemBox); addItemPanel.add(addItemButton); - JList<T> itemList = new JList<>(listModel); + JList<T> itemList = new JList<>(model); itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); - JButton removeItemButton = new JButton("Remove " + itemType); + JButton removeItemButton = new JButton("Remove " + type); addItemButton.addActionListener((ev) -> { - listModel.addElement( + model.addElement( addItemBox.getItemAt(addItemBox.getSelectedIndex())); }); removeItemButton.addActionListener((ev) -> { - listModel.remove(itemList.getSelectedIndex()); + model.remove(itemList.getSelectedIndex()); }); itemInputPanel.add(addItemPanel, BorderLayout.PAGE_START); @@ -72,4 +72,4 @@ public class DropdownListPanel extends JPanel { add(itemInputPanel); } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java index 54970ec..a05c06e 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/FormattedInputPanel.java @@ -19,6 +19,7 @@ import bjc.utils.gui.layout.HLayout; */ public class FormattedInputPanel<InputVal> extends JPanel { private static final long serialVersionUID = 5232016563558588031L; + private JFormattedTextField field; /** @@ -30,13 +31,13 @@ public class FormattedInputPanel<InputVal> extends JPanel { * The length of this panel * @param formatter * The formatter to use for input - * @param valueReciever + * @param reciever * The action to call whenever the value changes */ @SuppressWarnings("unchecked") public FormattedInputPanel(String label, int length, AbstractFormatter formatter, - Consumer<InputVal> valueReciever) { + Consumer<InputVal> reciever) { setLayout(new HLayout(2)); JLabel lab = new JLabel(label); @@ -47,7 +48,7 @@ public class FormattedInputPanel<InputVal> extends JPanel { field.addPropertyChangeListener("value", (event) -> { // This is safe, because InputVal should be the type of // whatever object the formatter is returning - valueReciever.accept((InputVal) field.getValue()); + reciever.accept((InputVal) field.getValue()); }); add(lab); diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java index 128dbfc..f7f2c26 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java @@ -15,7 +15,8 @@ import bjc.utils.gui.layout.HLayout; */ public class HolderOutputPanel extends JPanel { private static final long serialVersionUID = 166573313903782080L; - private Timer updateTimer; + + private Timer updater; private JLabel value; private int nDelay; private IHolder<String> val; @@ -40,7 +41,7 @@ public class HolderOutputPanel extends JPanel { JLabel label = new JLabel(lab); value = new JLabel("(stopped)"); - updateTimer = new Timer(nDelay, (event) -> { + updater = new Timer(nDelay, (event) -> { value.setText(valueHolder.getValue()); }); @@ -56,7 +57,7 @@ public class HolderOutputPanel extends JPanel { value.setText("(stopped)"); - updateTimer = new Timer(nDelay, (event) -> { + updater = new Timer(nDelay, (event) -> { value.setText(val.getValue()); }); } @@ -65,14 +66,14 @@ public class HolderOutputPanel extends JPanel { * Start updating the contents of the field from the holder */ public void startUpdating() { - updateTimer.start(); + updater.start(); } /** * Stop updating the contents of the field from the holder */ public void stopUpdating() { - updateTimer.stop(); + updater.stop(); value.setText(value.getText() + " (stopped)"); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java index 553d201..088be6c 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java @@ -29,39 +29,39 @@ public class ListParameterPanel<E> extends JPanel { /** * Create a new panel using the specified actions for doing things * - * @param addAction + * @param add * The action that provides items - * @param editAction + * @param edit * The action that edits items - * @param removeAction + * @param remove * The action that removes items */ - public ListParameterPanel(Supplier<E> addAction, - Consumer<E> editAction, Consumer<E> removeAction) { - this(addAction, editAction, removeAction, null); + public ListParameterPanel(Supplier<E> add, + Consumer<E> edit, Consumer<E> remove) { + this(add, edit, remove, null); } /** * Create a new panel using the specified actions for doing things * - * @param addAction + * @param add * The action that provides items - * @param editAction + * @param edit * The action that edits items - * @param removeAction + * @param remove * The action that removes items - * @param defaultValues + * @param defaults * The default values to put in the list */ - public ListParameterPanel(Supplier<E> addAction, - Consumer<E> editAction, Consumer<E> removeAction, - IList<E> defaultValues) { + public ListParameterPanel(Supplier<E> add, + Consumer<E> edit, Consumer<E> remove, + IList<E> defaults) { setLayout(new VLayout(2)); JList<E> list; - if (defaultValues != null) { - list = SimpleJList.buildFromList(defaultValues.toIterable()); + if (defaults != null) { + list = SimpleJList.buildFromList(defaults.toIterable()); } else { list = new JList<>(new DefaultListModel<>()); } @@ -72,15 +72,15 @@ public class ListParameterPanel<E> extends JPanel { int numButtons = 0; - if (addAction != null) { + if (add != null) { numButtons++; } - if (editAction != null) { + if (edit != null) { numButtons++; } - if (removeAction != null) { + if (remove != null) { numButtons++; } @@ -88,46 +88,46 @@ public class ListParameterPanel<E> extends JPanel { JButton addParam = null; - if (addAction != null) { + if (add != null) { addParam = new JButton("Add..."); addParam.addActionListener((event) -> { DefaultListModel< E> model = (DefaultListModel<E>) list.getModel(); - model.addElement(addAction.get()); + model.addElement(add.get()); }); } JButton editParam = null; - if (editAction != null) { + if (edit != null) { editParam = new JButton("Edit..."); editParam.addActionListener((event) -> { - editAction.accept(list.getSelectedValue()); + edit.accept(list.getSelectedValue()); }); } JButton removeParam = null; - if (removeAction != null) { + if (remove != null) { removeParam = new JButton("Remove..."); removeParam.addActionListener((event) -> { DefaultListModel< E> model = (DefaultListModel<E>) list.getModel(); - removeAction.accept(model.remove(list.getSelectedIndex())); + remove.accept(model.remove(list.getSelectedIndex())); }); } - if (addAction != null) { + if (add != null) { buttonPanel.add(addParam); } - if (editAction != null) { + if (edit != null) { buttonPanel.add(editParam); } - if (removeAction != null) { + if (remove != null) { buttonPanel.add(removeParam); } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java index e034b48..48230dd 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleListPanel.java @@ -24,16 +24,16 @@ import bjc.utils.gui.layout.HLayout; public class SimpleListPanel extends JPanel { private static final long serialVersionUID = 2719963952350133541L; - private static void addItem(DefaultListModel<String> listModel, - Predicate<String> itemVerifier, - Consumer<String> onVerificationFailure, + private static void addItem(DefaultListModel<String> model, + Predicate<String> verifier, + Consumer<String> onFailure, JTextField addItemField) { String potentialItem = addItemField.getText(); - if (itemVerifier == null || itemVerifier.test(potentialItem)) { - listModel.addElement(potentialItem); + if (verifier == null || verifier.test(potentialItem)) { + model.addElement(potentialItem); } else { - onVerificationFailure.accept(potentialItem); + onFailure.accept(potentialItem); } addItemField.setText(""); @@ -42,19 +42,19 @@ public class SimpleListPanel extends JPanel { /** * Create a new list panel * - * @param itemType + * @param type * The type of things in the list - * @param listModel + * @param model * The model to put items into - * @param itemVerifier + * @param verifier * The predicate to use to verify items - * @param onVerificationFailure + * @param onFailure * The function to call when an item doesn't verify */ - public SimpleListPanel(String itemType, - DefaultListModel<String> listModel, - Predicate<String> itemVerifier, - Consumer<String> onVerificationFailure) { + public SimpleListPanel(String type, + DefaultListModel<String> model, + Predicate<String> verifier, + Consumer<String> onFailure) { setLayout(new AutosizeLayout()); JPanel itemInputPanel = new JPanel(); @@ -64,30 +64,30 @@ public class SimpleListPanel extends JPanel { addItemPanel.setLayout(new HLayout(2)); JTextField addItemField = new JTextField(255); - JButton addItemButton = new JButton("Add " + itemType); + JButton addItemButton = new JButton("Add " + type); addItemPanel.add(addItemField); addItemPanel.add(addItemButton); - JList<String> itemList = new JList<>(listModel); + JList<String> itemList = new JList<>(model); itemList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); JScrollPane listScroller = new JScrollPane(itemList); - JButton removeItemButton = new JButton("Remove " + itemType); + JButton removeItemButton = new JButton("Remove " + type); addItemButton.addActionListener((ev) -> { - addItem(listModel, itemVerifier, onVerificationFailure, + addItem(model, verifier, onFailure, addItemField); }); addItemField.addActionListener((ev) -> { - addItem(listModel, itemVerifier, onVerificationFailure, + addItem(model, verifier, onFailure, addItemField); }); removeItemButton.addActionListener((ev) -> { - listModel.remove(itemList.getSelectedIndex()); + model.remove(itemList.getSelectedIndex()); }); itemInputPanel.add(addItemPanel, BorderLayout.PAGE_START); @@ -96,4 +96,4 @@ public class SimpleListPanel extends JPanel { add(itemInputPanel); } -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java index 7b138c5..bd39972 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java @@ -15,7 +15,7 @@ import javax.swing.SpinnerModel; public class SimpleSpinnerPanel extends JPanel { private static final long serialVersionUID = -4734279623645236868L; - /** + /* * The spinner being used */ public final JSpinner inputValue; @@ -30,9 +30,9 @@ public class SimpleSpinnerPanel extends JPanel { JLabel inputLabel = new JLabel(label); - inputValue = new JSpinner(model); + input = new JSpinner(model); add(inputLabel, BorderLayout.LINE_START); - add(inputValue, BorderLayout.CENTER); + add(input, BorderLayout.CENTER); } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java index 792db73..9de4d63 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java +++ b/BJC-Utils2/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java @@ -157,11 +157,11 @@ public class SliderInputPanel extends JPanel { if (slider.getValueIsAdjusting()) { // Do nothing } else { - int sliderVal = slider.getValue(); + int val = slider.getValue(); - field.setValue(sliderVal); + field.setValue(val); - action.accept(sliderVal); + action.accept(val); } }); diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java index 287c8a9..31ceecd 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/IPrecedent.java @@ -25,4 +25,4 @@ public interface IPrecedent { * @return The precedence of the attached object */ public int getPrecedence(); -}
\ No newline at end of file +} diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java index 99e3e60..fe046f4 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/ShuntingYard.java @@ -51,11 +51,6 @@ public class ShuntingYard<TokenType> { precedence = prec; } - /* - * (non-Javadoc) - * - * @see bjc.utils.parserutils.IPrecedent#getPrecedence() - */ @Override public int getPrecedence() { return precedence; @@ -65,13 +60,13 @@ public class ShuntingYard<TokenType> { private final class TokenShunter implements Consumer<String> { private IList<TokenType> output; private Deque<String> stack; - private Function<String, TokenType> transform; + private Function<String, TokenType> transformer; public TokenShunter(IList<TokenType> outpt, Deque<String> stack, - Function<String, TokenType> transform) { + Function<String, TokenType> transformer) { this.output = outpt; this.stack = stack; - this.transform = transform; + this.transformer = transformer; } @Override @@ -81,7 +76,7 @@ public class ShuntingYard<TokenType> { // Pop operators while there isn't a higher precedence one while (!stack.isEmpty() && isHigherPrec(token, stack.peek())) { - output.add(transform.apply(stack.pop())); + output.add(transformer.apply(stack.pop())); } // Put this operator onto the stack @@ -95,19 +90,19 @@ public class ShuntingYard<TokenType> { // Remove tokens up to a matching parenthesis while (!stack.peek().equals(swappedToken)) { - output.add(transform.apply(stack.pop())); + output.add(transformer.apply(stack.pop())); } // Remove the parenthesis stack.pop(); } else { // Just add the transformed token - output.add(transform.apply(token)); + output.add(transformer.apply(token)); } } } - /** + /* * Holds all the shuntable operations */ private IMap<String, IPrecedent> operators; @@ -138,11 +133,11 @@ public class ShuntingYard<TokenType> { * @param precedence * The precedence of the operator to add */ - public void addOp(String operatorToken, int precedence) { + public void addOp(String operator, int precedence) { // Create the precedence marker IPrecedent prec = IPrecedent.newSimplePrecedent(precedence); - this.addOp(operatorToken, prec); + this.addOp(operator, prec); } /** @@ -153,30 +148,30 @@ public class ShuntingYard<TokenType> { * @param precedence * The precedence of the operator */ - public void addOp(String operatorToken, IPrecedent precedence) { + public void addOp(String operator, IPrecedent precedence) { // Complain about trying to add an incorrect operator - if (operatorToken == null) { + if (operator == null) { throw new NullPointerException("Operator must not be null"); } else if(precedence == null) { throw new NullPointerException("Precedence must not be null"); } // Add the operator to the ones we handle - operators.put(operatorToken, precedence); + operators.put(operator, precedence); } - private boolean isHigherPrec(String leftOperator, String rightOperator) { + private boolean isHigherPrec(String left, String right) { // Check if the right operator exists - boolean operatorExists = operators.containsKey(rightOperator); + boolean exists = operators.containsKey(right); // If it doesn't, the left is higher precedence. - if (!operatorExists) { + if (!exists) { return false; } // Get the precedence of operators - int rightPrecedence = operators.get(rightOperator).getPrecedence(); - int leftPrecedence = operators.get(leftOperator).getPrecedence(); + int rightPrecedence = operators.get(right).getPrecedence(); + int leftPrecedence = operators.get(left).getPrecedence(); // Evaluate what we were asked return rightPrecedence >= leftPrecedence; @@ -187,16 +182,16 @@ public class ShuntingYard<TokenType> { * * @param input * The string to transform - * @param tokenTransformer + * @param transformer * The function to use to transform strings to tokens * @return A list of tokens in postfix notation */ public IList<TokenType> postfix(IList<String> input, - Function<String, TokenType> tokenTransformer) { + Function<String, TokenType> transformer) { // Check our input if (input == null) { throw new NullPointerException("Input must not be null"); - } else if (tokenTransformer == null) { + } else if (transformer == null) { throw new NullPointerException("Transformer must not be null"); } @@ -207,11 +202,11 @@ public class ShuntingYard<TokenType> { Deque<String> stack = new LinkedList<>(); // Shunt the tokens - input.forEach(new TokenShunter(output, stack, tokenTransformer)); + input.forEach(new TokenShunter(output, stack, transformer)); // Transform any resulting tokens stack.forEach((token) -> { - output.add(tokenTransformer.apply(token)); + output.add(transformer.apply(token)); }); return output; @@ -224,12 +219,12 @@ public class ShuntingYard<TokenType> { * The token representing the operator. If null, remove all * operators */ - public void removeOp(String token) { + public void removeOp(String operator) { // Check if we want to remove all operators - if (token == null) { + if (operator == null) { operators = new FunctionalMap<>(); } else { - operators.remove(token); + operators.remove(operator); } } } diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java index ff3a6b9..9953c00 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TokenTransformer.java @@ -52,11 +52,11 @@ final class TokenTransformer<TokenType> implements Consumer<TokenType> { } // Grab the two operands - ITree<TokenType> rightAST = queuedASTs.pop(); - ITree<TokenType> leftAST = queuedASTs.pop(); + ITree<TokenType> right = queuedASTs.pop(); + ITree<TokenType> left = queuedASTs.pop(); // Create a new AST - newAST = new Tree<>(element, leftAST, rightAST); + newAST = new Tree<>(element, left, right); } // Stick it onto the stack diff --git a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java index 0b61363..7f933c0 100644 --- a/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java +++ b/BJC-Utils2/src/main/java/bjc/utils/parserutils/TreeConstructor.java @@ -28,16 +28,16 @@ public class TreeConstructor { * The elements of the parse tree * @param tokens * The list of tokens to build a tree from - * @param operatorPredicate + * @param isOperator * The predicate to use to determine if something is a * operator * @return A AST from the expression */ public static <TokenType> ITree<TokenType> constructTree( IList<TokenType> tokens, - Predicate<TokenType> operatorPredicate) { + Predicate<TokenType> isOperator) { // Construct a tree with no special operators - return constructTree(tokens, operatorPredicate, (op) -> false, + return constructTree(tokens, isOperator, (op) -> false, null); } @@ -51,7 +51,7 @@ public class TreeConstructor { * The elements of the parse tree * @param tokens * The list of tokens to build a tree from - * @param operatorPredicate + * @param isOperator * The predicate to use to determine if something is a * operator * @param isSpecialOperator @@ -62,19 +62,19 @@ public class TreeConstructor { * @return A AST from the expression * * FIXME The handleSpecialOp function seems like an ugly - * interface. Maybe there's a better way to express how that - * works + * interface. Maybe there's a better way to express how + * that works. */ public static <TokenType> ITree<TokenType> constructTree( IList<TokenType> tokens, - Predicate<TokenType> operatorPredicate, + Predicate<TokenType> isOperator, Predicate<TokenType> isSpecialOperator, Function<TokenType, Function<Deque<ITree<TokenType>>, ITree<TokenType>>> handleSpecialOperator) { // Make sure our parameters are valid if (tokens == null) { throw new NullPointerException("Tokens must not be null"); - } else if (operatorPredicate == null) { + } else if (isOperator == null) { throw new NullPointerException( "Operator predicate must not be null"); } else if (isSpecialOperator == null) { @@ -89,7 +89,7 @@ public class TreeConstructor { // Transform each of the tokens tokens.forEach( - new TokenTransformer<>(initialState, operatorPredicate, + new TokenTransformer<>(initialState, isOperator, isSpecialOperator, handleSpecialOperator)); // Grab the tree from the state diff --git a/BJC-Utils2/tags b/BJC-Utils2/tags index bad0ac3..37dc4ec 100644 --- a/BJC-Utils2/tags +++ b/BJC-Utils2/tags @@ -3,7 +3,7 @@ !_TAG_PROGRAM_AUTHOR Darren Hiebert /dhiebert@users.sourceforge.net/ !_TAG_PROGRAM_NAME Exuberant Ctags // !_TAG_PROGRAM_URL http://ctags.sourceforge.net /official site/ -!_TAG_PROGRAM_VERSION 5.8 // +!_TAG_PROGRAM_VERSION 5.9~svn20110310 // ADD src/main/java/bjc/utils/parserutils/ShuntingYard.java /^ ADD(1),$/;" e enum:ShuntingYard.Operator file: AdjacencyMap src/main/java/bjc/utils/graph/AdjacencyMap.java /^ public AdjacencyMap(IList<T> vertices) {$/;" m class:AdjacencyMap AdjacencyMap src/main/java/bjc/utils/graph/AdjacencyMap.java /^public class AdjacencyMap<T> {$/;" c |
