diff --git a/Ant-Clean.xml b/Ant-Clean.xml index ebcf3977..22e810a1 100644 --- a/Ant-Clean.xml +++ b/Ant-Clean.xml @@ -31,8 +31,7 @@ - - + diff --git a/Ant-Common.xml b/Ant-Common.xml index f11eb74b..16dfc784 100644 --- a/Ant-Common.xml +++ b/Ant-Common.xml @@ -74,7 +74,13 @@ + srcdir="${basedir}/../onjava/"> + + + + @@ -90,6 +96,12 @@ + + + + testObject = new HashSet<>(); diff --git a/annotations/StackLStringTest.java b/annotations/StackLStringTest.java index 9a2d973f..1175f25e 100644 --- a/annotations/StackLStringTest.java +++ b/annotations/StackLStringTest.java @@ -2,7 +2,7 @@ // Applying @Unit to generics. package annotations; import com.mindviewinc.atunit.*; -import com.mindviewinc.util.*; +import onjava.*; public class StackLStringTest extends StackL { @Test void _push() { diff --git a/arrays/AlphabeticSearch.java b/arrays/AlphabeticSearch.java index 0fe2fc5e..27c4a1c8 100644 --- a/arrays/AlphabeticSearch.java +++ b/arrays/AlphabeticSearch.java @@ -1,7 +1,7 @@ // arrays/AlphabeticSearch.java // Searching with a Comparator. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class AlphabeticSearch { public static void main(String[] args) { diff --git a/arrays/ArrayOptions.java b/arrays/ArrayOptions.java index a6bbcc22..42ed6575 100644 --- a/arrays/ArrayOptions.java +++ b/arrays/ArrayOptions.java @@ -7,6 +7,7 @@ public class ArrayOptions { // Arrays of objects: BerylliumSphere[] a; // Local uninitialized variable BerylliumSphere[] b = new BerylliumSphere[5]; + // The references inside the array are // automatically initialized to null: System.out.println("b: " + Arrays.toString(b)); @@ -14,14 +15,17 @@ public class ArrayOptions { for(int i = 0; i < c.length; i++) if(c[i] == null) // Can test for null reference c[i] = new BerylliumSphere(); + // Aggregate initialization: BerylliumSphere[] d = { new BerylliumSphere(), new BerylliumSphere(), new BerylliumSphere() }; + // Dynamic aggregate initialization: a = new BerylliumSphere[]{ new BerylliumSphere(), new BerylliumSphere(), }; + // (Trailing comma is optional in both cases) System.out.println("a.length = " + a.length); System.out.println("b.length = " + b.length); @@ -33,6 +37,7 @@ public class ArrayOptions { // Arrays of primitives: int[] e; // Null reference int[] f = new int[5]; + // The primitives inside the array are // automatically initialized to zero: System.out.println("f: " + Arrays.toString(f)); @@ -40,6 +45,7 @@ public class ArrayOptions { for(int i = 0; i < g.length; i++) g[i] = i*i; int[] h = { 11, 47, 93 }; + // Compile error: variable e not initialized: //!print("e.length = " + e.length); System.out.println("f.length = " + f.length); diff --git a/arrays/ArraySearching.java b/arrays/ArraySearching.java index f99bd8f5..4fb3317a 100644 --- a/arrays/ArraySearching.java +++ b/arrays/ArraySearching.java @@ -2,7 +2,7 @@ // Using Arrays.binarySearch(). import java.util.*; import java.util.function.*; -import com.mindviewinc.util.*; +import onjava.*; public class ArraySearching { public static void main(String[] args) { diff --git a/arrays/CompType.java b/arrays/CompType.java index be0e1401..981bbce8 100644 --- a/arrays/CompType.java +++ b/arrays/CompType.java @@ -2,7 +2,7 @@ // Implementing Comparable in a class. import java.util.*; import java.util.function.*; -import com.mindviewinc.util.*; +import onjava.*; public class CompType implements Comparable { int i; diff --git a/arrays/ComparatorTest.java b/arrays/ComparatorTest.java index 1ef1b529..8921458f 100644 --- a/arrays/ComparatorTest.java +++ b/arrays/ComparatorTest.java @@ -1,7 +1,7 @@ // arrays/ComparatorTest.java // Implementing a Comparator for a class. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; class CompTypeComparator implements Comparator { public int compare(CompType o1, CompType o2) { diff --git a/arrays/PrimitiveConversionDemonstration.java b/arrays/PrimitiveConversionDemonstration.java index ec20cfa4..e3edb799 100644 --- a/arrays/PrimitiveConversionDemonstration.java +++ b/arrays/PrimitiveConversionDemonstration.java @@ -1,6 +1,6 @@ // arrays/PrimitiveConversionDemonstration.java import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class PrimitiveConversionDemonstration { public static void main(String[] args) { diff --git a/arrays/RandomSuppliersTest.java b/arrays/RandomSuppliersTest.java index 076959df..0f313ba3 100644 --- a/arrays/RandomSuppliersTest.java +++ b/arrays/RandomSuppliersTest.java @@ -1,5 +1,5 @@ // arrays/RandomSuppliersTest.java -import com.mindviewinc.util.*; +import onjava.*; public class RandomSuppliersTest { public static void main(String[] args) { diff --git a/arrays/Reverse.java b/arrays/Reverse.java index 0cadef57..734171aa 100644 --- a/arrays/Reverse.java +++ b/arrays/Reverse.java @@ -1,7 +1,7 @@ // arrays/Reverse.java // The Collections.reverseOrder() Comparator import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class Reverse { public static void main(String[] args) { diff --git a/arrays/StringSorting.java b/arrays/StringSorting.java index 1c18f567..edb24530 100644 --- a/arrays/StringSorting.java +++ b/arrays/StringSorting.java @@ -1,7 +1,7 @@ // arrays/StringSorting.java // Sorting an array of Strings. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class StringSorting { public static void main(String[] args) { diff --git a/arrays/SuppliersTest.java b/arrays/SuppliersTest.java index 252cf404..9860d596 100644 --- a/arrays/SuppliersTest.java +++ b/arrays/SuppliersTest.java @@ -1,6 +1,6 @@ // arrays/SuppliersTest.java import java.util.function.*; -import com.mindviewinc.util.*; +import onjava.*; public class SuppliersTest { public static int size = 10; diff --git a/arrays/TestArrayGeneration.java b/arrays/TestArrayGeneration.java index 9388d75d..d5262d52 100644 --- a/arrays/TestArrayGeneration.java +++ b/arrays/TestArrayGeneration.java @@ -1,7 +1,7 @@ // arrays/TestArrayGeneration.java // Test the tools that use generators to fill arrays. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class TestArrayGeneration { public static void main(String[] args) { diff --git a/arrays/TestGenerated.java b/arrays/TestGenerated.java index bbe46080..8059dfc7 100644 --- a/arrays/TestGenerated.java +++ b/arrays/TestGenerated.java @@ -1,6 +1,6 @@ // arrays/TestGenerated.java import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class TestGenerated { public static void main(String[] args) { diff --git a/build.xml b/build.xml index 0294e84c..70dc2438 100644 --- a/build.xml +++ b/build.xml @@ -30,28 +30,35 @@ polymorphism/build.xml interfaces/build.xml innerclasses/build.xml + functions/build.xml containers/build.xml + streams/build.xml exceptions/build.xml strings/build.xml typeinfo/build.xml generics/build.xml arrays/build.xml containersindepth/build.xml - io/build.xml - xml/build.xml + files/build.xml enums/build.xml annotations/build.xml concurrency/build.xml ui/build.xml swt/build.xml patterns/build.xml - references/build.xml - assertions/build.xml unittesting/build.xml - debugging/build.xml - logging/build.xml + assertions/build.xml + references/build.xml + iostreams/build.xml + standardio/build.xml + newio/build.xml + compression/build.xml + serialization/build.xml + preferences/build.xml network/build.xml remote/build.xml + logging/build.xml + debugging/build.xml staticchecking/build.xml "/> diff --git a/com/build.xml b/com/build.xml index e13085a3..4429a242 100644 --- a/com/build.xml +++ b/com/build.xml @@ -9,13 +9,6 @@ - - - - - - - diff --git a/com/mindviewinc/atunit/AtUnit.java b/com/mindviewinc/atunit/AtUnit.java index 4e5c6b77..d14c3eed 100644 --- a/com/mindviewinc/atunit/AtUnit.java +++ b/com/mindviewinc/atunit/AtUnit.java @@ -4,7 +4,7 @@ package com.mindviewinc.atunit; import java.lang.reflect.*; import java.io.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class AtUnit implements ProcessFiles.Strategy { static Class testClass; diff --git a/com/mindviewinc/atunit/ClassNameFinder.java b/com/mindviewinc/atunit/ClassNameFinder.java index 0f9591ab..226e99df 100644 --- a/com/mindviewinc/atunit/ClassNameFinder.java +++ b/com/mindviewinc/atunit/ClassNameFinder.java @@ -2,7 +2,7 @@ package com.mindviewinc.atunit; import java.io.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class ClassNameFinder { public static String thisClass(byte[] classBytes) { diff --git a/com/mindviewinc/util/FiveTuple.java b/com/mindviewinc/util/FiveTuple.java deleted file mode 100644 index f2deb630..00000000 --- a/com/mindviewinc/util/FiveTuple.java +++ /dev/null @@ -1,16 +0,0 @@ -// com/mindviewinc/util/FiveTuple.java -package com.mindviewinc.util; - -public class FiveTuple -extends FourTuple { - public final E fifth; - public FiveTuple(A a, B b, C c, D d, E e) { - super(a, b, c, d); - fifth = e; - } - @Override - public String toString() { - return "(" + first + ", " + second + ", " + - third + ", " + fourth + ", " + fifth + ")"; - } -} diff --git a/com/mindviewinc/util/FourTuple.java b/com/mindviewinc/util/FourTuple.java deleted file mode 100644 index 837127b0..00000000 --- a/com/mindviewinc/util/FourTuple.java +++ /dev/null @@ -1,16 +0,0 @@ -// com/mindviewinc/util/FourTuple.java -package com.mindviewinc.util; - -public class FourTuple - extends ThreeTuple { - public final D fourth; - public FourTuple(A a, B b, C c, D d) { - super(a, b, c); - fourth = d; - } - @Override - public String toString() { - return "(" + first + ", " + second + ", " + - third + ", " + fourth + ")"; - } -} diff --git a/com/mindviewinc/util/Null.java b/com/mindviewinc/util/Null.java deleted file mode 100644 index 5b618bc1..00000000 --- a/com/mindviewinc/util/Null.java +++ /dev/null @@ -1,3 +0,0 @@ -// com/mindviewinc/util/Null.java -package com.mindviewinc.util; -public interface Null {} diff --git a/com/mindviewinc/util/ThreeTuple.java b/com/mindviewinc/util/ThreeTuple.java deleted file mode 100644 index c5b129e7..00000000 --- a/com/mindviewinc/util/ThreeTuple.java +++ /dev/null @@ -1,14 +0,0 @@ -// com/mindviewinc/util/ThreeTuple.java -package com.mindviewinc.util; - -public class ThreeTuple extends TwoTuple { - public final C third; - public ThreeTuple(A a, B b, C c) { - super(a, b); - third = c; - } - @Override - public String toString() { - return "(" + first + ", " + second + ", " + third +")"; - } -} diff --git a/com/mindviewinc/util/Tuple.java b/com/mindviewinc/util/Tuple.java deleted file mode 100644 index 7dbc2cbd..00000000 --- a/com/mindviewinc/util/Tuple.java +++ /dev/null @@ -1,21 +0,0 @@ -// com/mindviewinc/util/Tuple.java -// Tuple library using type argument inference. -package com.mindviewinc.util; - -public class Tuple { - public static TwoTuple tuple(A a, B b) { - return new TwoTuple<>(a, b); - } - public static ThreeTuple - tuple(A a, B b, C c) { - return new ThreeTuple<>(a, b, c); - } - public static FourTuple - tuple(A a, B b, C c, D d) { - return new FourTuple<>(a, b, c, d); - } - public static - FiveTuple tuple(A a, B b, C c, D d, E e) { - return new FiveTuple<>(a, b, c, d, e); - } -} diff --git a/com/mindviewinc/util/TwoTuple.java b/com/mindviewinc/util/TwoTuple.java deleted file mode 100644 index 264bbc68..00000000 --- a/com/mindviewinc/util/TwoTuple.java +++ /dev/null @@ -1,12 +0,0 @@ -// com/mindviewinc/util/TwoTuple.java -package com.mindviewinc.util; - -public class TwoTuple { - public final A first; - public final B second; - public TwoTuple(A a, B b) { first = a; second = b; } - @Override - public String toString() { - return "(" + first + ", " + second + ")"; - } -} diff --git a/concurrency/AtomicIntegerTest.java b/concurrency/AtomicIntegerTest.java index e3467ba3..f1873f9e 100644 --- a/concurrency/AtomicIntegerTest.java +++ b/concurrency/AtomicIntegerTest.java @@ -2,7 +2,7 @@ import java.util.concurrent.*; import java.util.concurrent.atomic.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class AtomicIntegerTest implements Runnable { private AtomicInteger i = new AtomicInteger(0); diff --git a/concurrency/DaemonFromFactory.java b/concurrency/DaemonFromFactory.java index 82a3af82..5073a5f6 100644 --- a/concurrency/DaemonFromFactory.java +++ b/concurrency/DaemonFromFactory.java @@ -1,7 +1,7 @@ // concurrency/DaemonFromFactory.java // Using a Thread Factory to create daemons. import java.util.concurrent.*; -import com.mindviewinc.util.*; +import onjava.*; public class DaemonFromFactory implements Runnable { @Override diff --git a/concurrency/ExchangerDemo.java b/concurrency/ExchangerDemo.java index 92c1da4f..64393879 100644 --- a/concurrency/ExchangerDemo.java +++ b/concurrency/ExchangerDemo.java @@ -2,7 +2,7 @@ import java.util.concurrent.*; import java.util.*; import java.util.function.*; -import com.mindviewinc.util.*; +import onjava.*; class ExchangerProducer implements Runnable { private Supplier generator; diff --git a/concurrency/ListComparisons.java b/concurrency/ListComparisons.java index fd90dd49..077d101f 100644 --- a/concurrency/ListComparisons.java +++ b/concurrency/ListComparisons.java @@ -3,7 +3,7 @@ // Rough comparison of thread-safe List performance. import java.util.concurrent.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; abstract class ListTest extends Tester> { ListTest(String testId, int nReaders, int nWriters) { diff --git a/concurrency/MapComparisons.java b/concurrency/MapComparisons.java index f9a073f4..4df74cdd 100644 --- a/concurrency/MapComparisons.java +++ b/concurrency/MapComparisons.java @@ -3,7 +3,7 @@ // Rough comparison of thread-safe Map performance. import java.util.concurrent.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; abstract class MapTest extends Tester> { diff --git a/concurrency/Tester.java b/concurrency/Tester.java index b30dd190..2f777de9 100644 --- a/concurrency/Tester.java +++ b/concurrency/Tester.java @@ -1,7 +1,7 @@ // concurrency/Tester.java // Framework to test performance of concurrency containers. import java.util.concurrent.*; -import com.mindviewinc.util.*; +import onjava.*; public abstract class Tester { static int testReps = 10; diff --git a/containers/AdapterMethodIdiom.java b/containers/AdapterMethodIdiom.java index 477e97a7..4b185c3a 100644 --- a/containers/AdapterMethodIdiom.java +++ b/containers/AdapterMethodIdiom.java @@ -1,5 +1,5 @@ // containers/AdapterMethodIdiom.java -// The "Adapter Method" idiom uses for-each +// The "Adapter Method" idiom uses for-in // with additional kinds of Iterables. import java.util.*; diff --git a/containers/ApplesAndOrangesWithGenerics.java b/containers/ApplesAndOrangesWithGenerics.java index 522370cd..a1e34ca0 100644 --- a/containers/ApplesAndOrangesWithGenerics.java +++ b/containers/ApplesAndOrangesWithGenerics.java @@ -11,7 +11,7 @@ public class ApplesAndOrangesWithGenerics { for(Apple apple : apples) { System.out.println(apple.id()); } - // Using for-each: + // Using for-in: for(Apple c : apples) System.out.println(c.id()); } diff --git a/containers/ArrayIsNotIterable.java b/containers/ArrayIsNotIterable.java index 509b7e27..551d94bd 100644 --- a/containers/ArrayIsNotIterable.java +++ b/containers/ArrayIsNotIterable.java @@ -9,7 +9,7 @@ public class ArrayIsNotIterable { public static void main(String[] args) { test(Arrays.asList(1, 2, 3)); String[] strings = { "A", "B", "C" }; - // An array works in for-each, but it's not Iterable: + // An array works in for-in, but it's not Iterable: //! test(strings); // You must explicitly convert it to an Iterable: test(Arrays.asList(strings)); diff --git a/containers/ContainerMethods.java b/containers/ContainerMethods.java index c78cb5f1..0adb67a9 100644 --- a/containers/ContainerMethods.java +++ b/containers/ContainerMethods.java @@ -1,5 +1,5 @@ // containers/ContainerMethods.java -import com.mindviewinc.util.*; +import onjava.*; public class ContainerMethods { public static void main(String[] args) { @@ -8,7 +8,7 @@ public class ContainerMethods { } /* Output: Collection: [add, addAll, clear, contains, containsAll, -equals, for-each, hashCode, isEmpty, iterator, +equals, forEach, hashCode, isEmpty, iterator, parallelStream, remove, removeAll, removeIf, retainAll, size, spliterator, stream, toArray] Interfaces in Collection: [Iterable] @@ -42,7 +42,7 @@ Interfaces in Queue: [Collection] PriorityQueue extends Queue, adds: [comparator] Interfaces in PriorityQueue: [Serializable] Map: [clear, compute, computeIfAbsent, computeIfPresent, -containsKey, containsValue, entrySet, equals, for-each, get, +containsKey, containsValue, entrySet, equals, forEach, get, getOrDefault, hashCode, isEmpty, keySet, merge, put, putAll, putIfAbsent, remove, replace, replaceAll, size, values] diff --git a/containers/ForEachCollections.java b/containers/ForInCollections.java similarity index 72% rename from containers/ForEachCollections.java rename to containers/ForInCollections.java index 91c0a6eb..913ba65f 100644 --- a/containers/ForEachCollections.java +++ b/containers/ForInCollections.java @@ -1,8 +1,8 @@ -// containers/ForEachCollections.java -// All collections work with for-each. +// containers/ForInCollections.java +// All collections work with for-in. import java.util.*; -public class ForEachCollections { +public class ForInCollections { public static void main(String[] args) { Collection cs = new LinkedList<>(); Collections.addAll(cs, diff --git a/containers/IterableClass.java b/containers/IterableClass.java index c934f0ea..0a7035d8 100644 --- a/containers/IterableClass.java +++ b/containers/IterableClass.java @@ -1,5 +1,5 @@ // containers/IterableClass.java -// Anything Iterable works with for-each. +// Anything Iterable works with for-in. import java.util.*; public class IterableClass implements Iterable { diff --git a/containers/StackCollision.java b/containers/StackCollision.java index c858468e..9e44e871 100644 --- a/containers/StackCollision.java +++ b/containers/StackCollision.java @@ -2,8 +2,7 @@ public class StackCollision { public static void main(String[] args) { - com.mindviewinc.util.Stack stack = - new com.mindviewinc.util.Stack<>(); + onjava.Stack stack = new onjava.Stack<>(); for(String s : "My dog has fleas".split(" ")) stack.push(s); while(!stack.empty()) diff --git a/containers/StackTest.java b/containers/StackTest.java index a09d60fb..bfef8f30 100644 --- a/containers/StackTest.java +++ b/containers/StackTest.java @@ -1,5 +1,5 @@ // containers/StackTest.java -import com.mindviewinc.util.*; +import onjava.*; public class StackTest { public static void main(String[] args) { diff --git a/containers/UniqueWords.java b/containers/UniqueWords.java index 43318e5f..22a28ea0 100644 --- a/containers/UniqueWords.java +++ b/containers/UniqueWords.java @@ -1,6 +1,6 @@ // containers/UniqueWords.java import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class UniqueWords { public static void main(String[] args) { diff --git a/containers/UniqueWordsAlphabetic.java b/containers/UniqueWordsAlphabetic.java index b501c3eb..2844b73a 100644 --- a/containers/UniqueWordsAlphabetic.java +++ b/containers/UniqueWordsAlphabetic.java @@ -1,7 +1,7 @@ // containers/UniqueWordsAlphabetic.java // Producing an alphabetic listing. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class UniqueWordsAlphabetic { public static void main(String[] args) { diff --git a/containers/build.xml b/containers/build.xml index e35111c0..629ac32b 100644 --- a/containers/build.xml +++ b/containers/build.xml @@ -17,7 +17,7 @@ - + diff --git a/containersindepth/CollectionDataGeneration.java b/containersindepth/CollectionDataGeneration.java index 0a536e9f..1c25fcb5 100644 --- a/containersindepth/CollectionDataGeneration.java +++ b/containersindepth/CollectionDataGeneration.java @@ -1,7 +1,7 @@ // containersindepth/CollectionDataGeneration.java // Using the Suppliers defined in the Arrays chapter. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class CollectionDataGeneration { public static void main(String[] args) { diff --git a/containersindepth/CollectionDataTest.java b/containersindepth/CollectionDataTest.java index 967d2b00..84f69554 100644 --- a/containersindepth/CollectionDataTest.java +++ b/containersindepth/CollectionDataTest.java @@ -1,7 +1,7 @@ // containersindepth/CollectionDataTest.java import java.util.*; import java.util.function.*; -import com.mindviewinc.util.*; +import onjava.*; class Government implements Supplier { String[] foundation = ("strange women lying in ponds " + diff --git a/containersindepth/CollectionMethods.java b/containersindepth/CollectionMethods.java index 0d8eeb2f..3a6ed80f 100644 --- a/containersindepth/CollectionMethods.java +++ b/containersindepth/CollectionMethods.java @@ -1,7 +1,7 @@ // containersindepth/CollectionMethods.java // Things you can do with all Collections. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class CollectionMethods { public static void main(String[] args) { diff --git a/containersindepth/CountedString.java b/containersindepth/CountedString.java index 9e94f6be..7d44ae93 100644 --- a/containersindepth/CountedString.java +++ b/containersindepth/CountedString.java @@ -11,7 +11,7 @@ public class CountedString { s = str; created.add(s); // id is the total number of instances - // of this string in use by CountedString: + // of this String in use by CountedString: for(String s2 : created) if(s2.equals(s)) id++; diff --git a/containersindepth/DequeTest.java b/containersindepth/DequeTest.java index 417778a7..2c169c06 100644 --- a/containersindepth/DequeTest.java +++ b/containersindepth/DequeTest.java @@ -1,5 +1,5 @@ // containersindepth/DequeTest.java -import com.mindviewinc.util.*; +import onjava.*; public class DequeTest { static void fillTest(Deque deque) { diff --git a/containersindepth/Enumerations.java b/containersindepth/Enumerations.java index 48bc114d..24acb9aa 100644 --- a/containersindepth/Enumerations.java +++ b/containersindepth/Enumerations.java @@ -1,7 +1,7 @@ // containersindepth/Enumerations.java // Java 1.0/1.1 Vector and Enumeration. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class Enumerations { public static void main(String[] args) { diff --git a/containersindepth/LinkedHashMapDemo.java b/containersindepth/LinkedHashMapDemo.java index a5041e3c..d1317cc2 100644 --- a/containersindepth/LinkedHashMapDemo.java +++ b/containersindepth/LinkedHashMapDemo.java @@ -1,7 +1,7 @@ // containersindepth/LinkedHashMapDemo.java // What you can do with a LinkedHashMap. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class LinkedHashMapDemo { public static void main(String[] args) { diff --git a/containersindepth/ListPerformance.java b/containersindepth/ListPerformance.java index 53d5230a..e5e86003 100644 --- a/containersindepth/ListPerformance.java +++ b/containersindepth/ListPerformance.java @@ -2,7 +2,7 @@ // Demonstrates performance differences in Lists. // {Args: 100 500} Small to keep build testing short import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class ListPerformance { static Random rand = new Random(); diff --git a/containersindepth/Lists.java b/containersindepth/Lists.java index da55bdc0..fd4dacf4 100644 --- a/containersindepth/Lists.java +++ b/containersindepth/Lists.java @@ -1,7 +1,7 @@ // containersindepth/Lists.java // Things you can do with Lists. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class Lists { private static boolean b; diff --git a/containersindepth/MapDataTest.java b/containersindepth/MapDataTest.java index 9a01276e..39c4626b 100644 --- a/containersindepth/MapDataTest.java +++ b/containersindepth/MapDataTest.java @@ -1,7 +1,7 @@ // containersindepth/MapDataTest.java import java.util.*; import java.util.function.*; -import com.mindviewinc.util.*; +import onjava.*; class Letters implements Supplier>, Iterable { diff --git a/containersindepth/Maps.java b/containersindepth/Maps.java index 42b89144..d3fadf26 100644 --- a/containersindepth/Maps.java +++ b/containersindepth/Maps.java @@ -2,7 +2,7 @@ // Things you can do with Maps. import java.util.concurrent.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class Maps { public static void printKeys(Map map) { diff --git a/containersindepth/QueueBehavior.java b/containersindepth/QueueBehavior.java index c7fa0c47..d58fb553 100644 --- a/containersindepth/QueueBehavior.java +++ b/containersindepth/QueueBehavior.java @@ -3,7 +3,7 @@ import java.util.concurrent.*; import java.util.*; import java.util.function.*; -import com.mindviewinc.util.*; +import onjava.*; public class QueueBehavior { private static int count = 10; diff --git a/containersindepth/ReadOnly.java b/containersindepth/ReadOnly.java index 36f37f6b..46dfe950 100644 --- a/containersindepth/ReadOnly.java +++ b/containersindepth/ReadOnly.java @@ -1,7 +1,7 @@ // containersindepth/ReadOnly.java // Using the Collections.unmodifiable methods. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class ReadOnly { static Collection data = diff --git a/containersindepth/SimpleHashMap.java b/containersindepth/SimpleHashMap.java index a267ac48..d2953c66 100644 --- a/containersindepth/SimpleHashMap.java +++ b/containersindepth/SimpleHashMap.java @@ -1,7 +1,7 @@ // containersindepth/SimpleHashMap.java // A demonstration hashed Map. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class SimpleHashMap extends AbstractMap { // Choose a prime number for the hash table diff --git a/containersindepth/SlowMap.java b/containersindepth/SlowMap.java index 252308d7..60dde958 100644 --- a/containersindepth/SlowMap.java +++ b/containersindepth/SlowMap.java @@ -1,7 +1,7 @@ // containersindepth/SlowMap.java // A Map implemented with ArrayLists. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class SlowMap extends AbstractMap { private List keys = new ArrayList<>(); diff --git a/containersindepth/SortedMapDemo.java b/containersindepth/SortedMapDemo.java index 94aa3b09..ad4bfad5 100644 --- a/containersindepth/SortedMapDemo.java +++ b/containersindepth/SortedMapDemo.java @@ -1,7 +1,7 @@ // containersindepth/SortedMapDemo.java // What you can do with a TreeMap. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class SortedMapDemo { public static void main(String[] args) { diff --git a/containersindepth/Stacks.java b/containersindepth/Stacks.java index e1a654fa..c9e6e3a6 100644 --- a/containersindepth/Stacks.java +++ b/containersindepth/Stacks.java @@ -28,8 +28,8 @@ public class Stacks { // Using the Stack class from // the Containers Chapter: - com.mindviewinc.util.Stack stack2 = - new com.mindviewinc.util.Stack<>(); + onjava.Stack stack2 = + new onjava.Stack<>(); for(Month m : Month.values()) stack2.push(m.toString()); System.out.println("stack2 = " + stack2); diff --git a/control/BreakAndContinue.java b/control/BreakAndContinue.java index 0e2395f9..e6fd584e 100644 --- a/control/BreakAndContinue.java +++ b/control/BreakAndContinue.java @@ -1,6 +1,6 @@ // control/BreakAndContinue.java // Demonstrates break and continue keywords. -import static com.mindviewinc.util.Range.*; +import static onjava.Range.*; public class BreakAndContinue { public static void main(String[] args) { @@ -10,7 +10,7 @@ public class BreakAndContinue { System.out.println(i + " "); } System.out.println(); - // Using forEach: + // Using for-in: for(int i : range(100)) { if(i == 74) break; // Out of for loop if(i % 9 != 0) continue; // Next iteration diff --git a/control/ForEachFloat.java b/control/ForInFloat.java similarity index 86% rename from control/ForEachFloat.java rename to control/ForInFloat.java index f37c1e34..7a60a826 100644 --- a/control/ForEachFloat.java +++ b/control/ForInFloat.java @@ -1,7 +1,7 @@ -// control/ForEachFloat.java +// control/ForInFloat.java import java.util.*; -public class ForEachFloat { +public class ForInFloat { public static void main(String[] args) { Random rand = new Random(47); float f[] = new float[10]; diff --git a/control/ForEachInt.java b/control/ForInInt.java similarity index 66% rename from control/ForEachInt.java rename to control/ForInInt.java index 49dc777b..e23830e5 100644 --- a/control/ForEachInt.java +++ b/control/ForInInt.java @@ -1,7 +1,7 @@ -// control/ForEachInt.java -import static com.mindviewinc.util.Range.*; +// control/ForInInt.java +import static onjava.Range.*; -public class ForEachInt { +public class ForInInt { public static void main(String[] args) { for(int i : range(10)) // 0..9 System.out.print(i + " "); @@ -12,10 +12,14 @@ public class ForEachInt { for(int i : range(5, 20, 3)) // 5..20 step 3 System.out.print(i + " "); System.out.println(); + for(int i : range(20, 5, -3)) // Count down + System.out.print(i + " "); + System.out.println(); } } /* Output: 0 1 2 3 4 5 6 7 8 9 5 6 7 8 9 5 8 11 14 17 +20 17 14 11 8 */ diff --git a/control/ForEachString.java b/control/ForInString.java similarity index 76% rename from control/ForEachString.java rename to control/ForInString.java index 3b371b7f..b73675eb 100644 --- a/control/ForEachString.java +++ b/control/ForInString.java @@ -1,6 +1,6 @@ -// control/ForEachString.java +// control/ForInString.java -public class ForEachString { +public class ForInString { public static void main(String[] args) { for(char c : "An African Swallow".toCharArray()) System.out.println(c + " "); diff --git a/control/build.xml b/control/build.xml index 1adb5656..c3353b15 100644 --- a/control/build.xml +++ b/control/build.xml @@ -9,9 +9,9 @@ - - - + + + diff --git a/enums/EnumClass.java b/enums/EnumClass.java index b28c06e8..3f3b4c03 100644 --- a/enums/EnumClass.java +++ b/enums/EnumClass.java @@ -14,7 +14,7 @@ public class EnumClass { System.out.println(s.name()); System.out.println("----------------------"); } - // Produce an enum value from a string name: + // Produce an enum value from a String name: for(String s : "HANGING CRAWLING GROUND".split(" ")) { Shrubbery shrub = Enum.valueOf(Shrubbery.class, s); System.out.println(shrub); diff --git a/enums/PostOffice.java b/enums/PostOffice.java index 21b3925b..e36b05a4 100644 --- a/enums/PostOffice.java +++ b/enums/PostOffice.java @@ -1,7 +1,7 @@ // enums/PostOffice.java // Modeling a post office. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; class Mail { // The NO's lower the probability of random selection: diff --git a/enums/RandomTest.java b/enums/RandomTest.java index 0e5d4d66..2fc0c88a 100644 --- a/enums/RandomTest.java +++ b/enums/RandomTest.java @@ -1,5 +1,5 @@ // enums/RandomTest.java -import com.mindviewinc.util.*; +import onjava.*; enum Activity { SITTING, LYING, STANDING, HOPPING, RUNNING, DODGING, JUMPING, FALLING, FLYING } diff --git a/enums/Reflection.java b/enums/Reflection.java index b9c7d713..d5f84451 100644 --- a/enums/Reflection.java +++ b/enums/Reflection.java @@ -2,7 +2,7 @@ // Analyzing enums using reflection. import java.lang.reflect.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; enum Explore { HERE, THERE } diff --git a/enums/RoShamBo.java b/enums/RoShamBo.java index 3ff59784..9c7d1dd3 100644 --- a/enums/RoShamBo.java +++ b/enums/RoShamBo.java @@ -1,7 +1,7 @@ // enums/RoShamBo.java // Common tools for RoShamBo examples. package enums; -import com.mindviewinc.util.*; +import onjava.*; public class RoShamBo { public static > diff --git a/enums/SecurityCategory.java b/enums/SecurityCategory.java index 33fd9129..ae5f2ba5 100644 --- a/enums/SecurityCategory.java +++ b/enums/SecurityCategory.java @@ -1,6 +1,6 @@ // enums/SecurityCategory.java // More succinct subcategorization of enums. -import com.mindviewinc.util.*; +import onjava.*; enum SecurityCategory { STOCK(Security.Stock.class), BOND(Security.Bond.class); diff --git a/enums/VendingMachine.java b/enums/VendingMachine.java index 55f161a4..eb789760 100644 --- a/enums/VendingMachine.java +++ b/enums/VendingMachine.java @@ -2,7 +2,7 @@ // {Args: VendingMachineInput.txt} import java.util.*; import java.util.function.*; -import com.mindviewinc.util.*; +import onjava.*; enum Category { MONEY(Input.NICKEL, Input.DIME, diff --git a/enums/menu/Course.java b/enums/menu/Course.java index 44e2128e..791bc0a6 100644 --- a/enums/menu/Course.java +++ b/enums/menu/Course.java @@ -1,6 +1,6 @@ // enums/menu/Course.java package enums.menu; -import com.mindviewinc.util.*; +import onjava.*; public enum Course { APPETIZER(Food.Appetizer.class), diff --git a/enums/menu/Meal2.java b/enums/menu/Meal2.java index ca3a5987..f595a409 100644 --- a/enums/menu/Meal2.java +++ b/enums/menu/Meal2.java @@ -1,6 +1,6 @@ // enums/menu/Meal2.java package enums.menu; -import com.mindviewinc.util.*; +import onjava.*; public enum Meal2 { APPETIZER(Food.Appetizer.class), diff --git a/exceptions/DynamicFields.java b/exceptions/DynamicFields.java index 1654ad28..97bc0f56 100644 --- a/exceptions/DynamicFields.java +++ b/exceptions/DynamicFields.java @@ -89,7 +89,8 @@ public class DynamicFields { df.setField("d", "A new value for d"); df.setField("number3", 11); System.out.println("df: " + df); - System.out.println("df.getField(\"d\") : " + df.getField("d")); + System.out.println("df.getField(\"d\") : " + + df.getField("d")); Object field = df.setField("d", null); // Exception } catch(NoSuchFieldException | DynamicFieldsException e) { diff --git a/io/DirList.java b/files/DirList.java similarity index 97% rename from io/DirList.java rename to files/DirList.java index aa8507dd..8faaa2f6 100644 --- a/io/DirList.java +++ b/files/DirList.java @@ -1,4 +1,4 @@ -// io/DirList.java +// files/DirList.java // Display a directory listing using regular expressions. // {Args: "D.*\.java"} import java.util.regex.*; diff --git a/io/DirList2.java b/files/DirList2.java similarity index 97% rename from io/DirList2.java rename to files/DirList2.java index 0927ffb2..4016cf86 100644 --- a/io/DirList2.java +++ b/files/DirList2.java @@ -1,4 +1,4 @@ -// io/DirList2.java +// files/DirList2.java // Uses anonymous inner classes. // {Args: "D.*\.java"} import java.util.regex.*; diff --git a/io/DirList3.java b/files/DirList3.java similarity index 97% rename from io/DirList3.java rename to files/DirList3.java index 36f4e17b..8b6137b2 100644 --- a/io/DirList3.java +++ b/files/DirList3.java @@ -1,4 +1,4 @@ -// io/DirList3.java +// files/DirList3.java // Building the anonymous inner class "in-place." // {Args: "D.*\.java"} import java.util.regex.*; diff --git a/io/DirectoryDemo.java b/files/DirectoryDemo.java similarity index 94% rename from io/DirectoryDemo.java rename to files/DirectoryDemo.java index 8d42a988..7b3a429c 100644 --- a/io/DirectoryDemo.java +++ b/files/DirectoryDemo.java @@ -1,7 +1,7 @@ -// io/DirectoryDemo.java +// files/DirectoryDemo.java // Sample use of Directory utilities. import java.io.*; -import com.mindviewinc.util.*; +import onjava.*; public class DirectoryDemo { public static void main(String[] args) { diff --git a/io/MakeDirectories.java b/files/MakeDirectories.java similarity index 98% rename from io/MakeDirectories.java rename to files/MakeDirectories.java index 7b41dc77..946c35a1 100644 --- a/io/MakeDirectories.java +++ b/files/MakeDirectories.java @@ -1,4 +1,4 @@ -// io/MakeDirectories.java +// files/MakeDirectories.java // Demonstrates using the File class to // create directories and manipulate files. // {Args: MakeDirectoriesTest} diff --git a/io/build.xml b/files/build.xml similarity index 92% rename from io/build.xml rename to files/build.xml index 408021e4..d155baa3 100644 --- a/io/build.xml +++ b/files/build.xml @@ -1,7 +1,7 @@ - + diff --git a/generics/BasicSupplierDemo.java b/generics/BasicSupplierDemo.java index 1c41c2c6..d434b92e 100644 --- a/generics/BasicSupplierDemo.java +++ b/generics/BasicSupplierDemo.java @@ -1,5 +1,5 @@ // generics/BasicSupplierDemo.java -import com.mindviewinc.util.*; +import onjava.*; import java.util.function.*; public class BasicSupplierDemo { diff --git a/generics/DynamicProxyMixin.java b/generics/DynamicProxyMixin.java index e99c676e..0d49509f 100644 --- a/generics/DynamicProxyMixin.java +++ b/generics/DynamicProxyMixin.java @@ -1,21 +1,21 @@ // generics/DynamicProxyMixin.java import java.lang.reflect.*; import java.util.*; -import com.mindviewinc.util.*; -import static com.mindviewinc.util.Tuple.*; +import onjava.*; +import static onjava.Tuple.*; class MixinProxy implements InvocationHandler { Map delegatesByMethod; @SuppressWarnings("unchecked") - public MixinProxy(TwoTuple>... pairs) { + public MixinProxy(Tuple2>... pairs) { delegatesByMethod = new HashMap<>(); - for(TwoTuple> pair : pairs) { - for(Method method : pair.second.getMethods()) { + for(Tuple2> pair : pairs) { + for(Method method : pair._2.getMethods()) { String methodName = method.getName(); // The first interface in the map // implements the method. if(!delegatesByMethod.containsKey(methodName)) - delegatesByMethod.put(methodName, pair.first); + delegatesByMethod.put(methodName, pair._1); } } } @@ -27,13 +27,13 @@ class MixinProxy implements InvocationHandler { return method.invoke(delegate, args); } @SuppressWarnings("unchecked") - public static Object newInstance(TwoTuple... pairs) { + public static Object newInstance(Tuple2... pairs) { Class[] interfaces = new Class[pairs.length]; for(int i = 0; i < pairs.length; i++) { - interfaces[i] = (Class)pairs[i].second; + interfaces[i] = (Class)pairs[i]._2; } ClassLoader cl = - pairs[0].first.getClass().getClassLoader(); + pairs[0]._1.getClass().getClassLoader(); return Proxy.newProxyInstance( cl, interfaces, new MixinProxy(pairs)); } diff --git a/generics/Functional.java b/generics/Functional.java index 2bad61db..bfd04feb 100644 --- a/generics/Functional.java +++ b/generics/Functional.java @@ -31,7 +31,7 @@ public class Functional { // object can act as a collecting parameter, so it is // returned at the end. public static Collector - forEach(Iterable seq, Collector func) { + forIn(Iterable seq, Collector func) { for(T t : seq) func.function(t); return func; @@ -132,10 +132,10 @@ public class Functional { System.out.println(filter(li, new GreaterThan<>(4))); - System.out.println(forEach(li, + System.out.println(forIn(li, new MultiplyingIntegerCollector()).result()); - System.out.println(forEach(filter(li, new GreaterThan<>(4)), + System.out.println(forIn(filter(li, new GreaterThan<>(4)), new MultiplyingIntegerCollector()).result()); MathContext mc = new MathContext(7); diff --git a/generics/PrimitiveGenericTest.java b/generics/PrimitiveGenericTest.java index 07eeae41..2cae004f 100644 --- a/generics/PrimitiveGenericTest.java +++ b/generics/PrimitiveGenericTest.java @@ -1,5 +1,5 @@ // generics/PrimitiveGenericTest.java -import com.mindviewinc.util.*; +import onjava.*; import java.util.function.*; // Fill an array using a generator: diff --git a/generics/TupleList.java b/generics/TupleList.java index 1b40a90d..9b1aee1f 100644 --- a/generics/TupleList.java +++ b/generics/TupleList.java @@ -1,16 +1,16 @@ // generics/TupleList.java // Combining generic types to make complex generic types. import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class TupleList -extends ArrayList> { +extends ArrayList> { public static void main(String[] args) { TupleList tl = new TupleList<>(); tl.add(TupleTest.h()); tl.add(TupleTest.h()); - for(FourTuple i: tl) + for(Tuple4 i: tl) System.out.println(i); } } diff --git a/generics/TupleTest.java b/generics/TupleTest.java index c2148a56..4e65198b 100644 --- a/generics/TupleTest.java +++ b/generics/TupleTest.java @@ -1,33 +1,33 @@ // generics/TupleTest.java -import com.mindviewinc.util.*; +import onjava.*; class Amphibian {} class Vehicle {} public class TupleTest { - static TwoTuple f() { + static Tuple2 f() { // Autoboxing converts the int to Integer: - return new TwoTuple<>("hi", 47); + return new Tuple2<>("hi", 47); } - static ThreeTuple g() { - return new ThreeTuple<>(new Amphibian(), "hi", 47); + static Tuple3 g() { + return new Tuple3<>(new Amphibian(), "hi", 47); } static - FourTuple h() { + Tuple4 h() { return - new FourTuple<>( + new Tuple4<>( new Vehicle(), new Amphibian(), "hi", 47); } static - FiveTuple k(){ + Tuple5 k(){ return new - FiveTuple<>( + Tuple5<>( new Vehicle(), new Amphibian(), "hi", 47, 11.1); } public static void main(String[] args) { - TwoTuple ttsi = f(); + Tuple2 ttsi = f(); System.out.println(ttsi); - // ttsi.first = "there"; // Compile error: final + // ttsi._1 = "there"; // Compile error: final System.out.println(g()); System.out.println(h()); System.out.println(k()); diff --git a/generics/TupleTest2.java b/generics/TupleTest2.java index b5b52417..2b5a8439 100644 --- a/generics/TupleTest2.java +++ b/generics/TupleTest2.java @@ -1,26 +1,26 @@ // generics/TupleTest2.java -import com.mindviewinc.util.*; -import static com.mindviewinc.util.Tuple.*; +import onjava.*; +import static onjava.Tuple.*; public class TupleTest2 { - static TwoTuple f() { + static Tuple2 f() { return tuple("hi", 47); } - static TwoTuple f2() { return tuple("hi", 47); } - static ThreeTuple g() { + static Tuple2 f2() { return tuple("hi", 47); } + static Tuple3 g() { return tuple(new Amphibian(), "hi", 47); } static - FourTuple h() { + Tuple4 h() { return tuple(new Vehicle(), new Amphibian(), "hi", 47); } static - FiveTuple k(){ + Tuple5 k(){ return tuple(new Vehicle(), new Amphibian(), "hi", 47, 11.1); } public static void main(String[] args) { - TwoTuple ttsi = f(); + Tuple2 ttsi = f(); System.out.println(ttsi); System.out.println(f2()); System.out.println(g()); diff --git a/generics/WatercolorSets.java b/generics/WatercolorSets.java index b5cebec2..d950f041 100644 --- a/generics/WatercolorSets.java +++ b/generics/WatercolorSets.java @@ -1,7 +1,7 @@ // generics/WatercolorSets.java import generics.watercolors.*; import java.util.*; -import static com.mindviewinc.util.Sets.*; +import static onjava.Sets.*; import static generics.watercolors.Watercolors.*; public class WatercolorSets { diff --git a/housekeeping/TerminationCondition.java b/housekeeping/TerminationCondition.java index b14329f1..0873f523 100644 --- a/housekeeping/TerminationCondition.java +++ b/housekeeping/TerminationCondition.java @@ -1,7 +1,7 @@ // housekeeping/TerminationCondition.java // Using finalize() to detect an object that // hasn't been properly cleaned up. -import com.mindviewinc.util.*; +import onjava.*; class Book { boolean checkedOut = false; diff --git a/logging/ConfigureLogging.java b/logging/ConfigureLogging.java index 60e5b3d4..7359792c 100644 --- a/logging/ConfigureLogging.java +++ b/logging/ConfigureLogging.java @@ -6,7 +6,7 @@ public class ConfigureLogging { static Logger lgr = Logger.getLogger("com"), lgr2 = Logger.getLogger("com.mindviewinc"), - util= Logger.getLogger("com.mindviewinc.util"), + util= Logger.getLogger("onjava"), test= Logger.getLogger("com.mindviewinc.test"), rand = Logger.getLogger("random"); public ConfigureLogging() { @@ -42,7 +42,7 @@ public class ConfigureLogging { /* Output: Logger Name : net Level: SEVERE Logger Name : com.mindviewinc Level: FINEST -Logger Name : com.mindviewinc.util Level: INFO +Logger Name : onjava Level: INFO Logger Name : com.mindviewinc.test Level: FINER Logger Name : random Level: SEVERE ___[ Error Output ]___ diff --git a/logging/LoggingLevelManipulation.java b/logging/LoggingLevelManipulation.java index d21afed9..6e2a1b49 100644 --- a/logging/LoggingLevelManipulation.java +++ b/logging/LoggingLevelManipulation.java @@ -6,7 +6,7 @@ public class LoggingLevelManipulation { private static Logger lgr = Logger.getLogger("com"), lgr2 = Logger.getLogger("com.mindviewinc"), - util= Logger.getLogger("com.mindviewinc.util"), + util= Logger.getLogger("onjava"), test= Logger.getLogger("com.mindviewinc.test"), rand = Logger.getLogger("random"); static void printLogMessages(Logger logger) { @@ -59,18 +59,18 @@ public class LoggingLevelManipulation { } /* Output: -- printing levels -- net : null com.mindviewinc : null -com.mindviewinc.util : null com.mindviewinc.test : null +onjava : null com.mindviewinc.test : null random : null -- printing levels -- net : SEVERE com.mindviewinc : null -com.mindviewinc.util : null com.mindviewinc.test : null +onjava : null com.mindviewinc.test : null random : null net level: SEVERE -- printing levels -- net : SEVERE com.mindviewinc : null -com.mindviewinc.util : FINEST com.mindviewinc.test : FINEST +onjava : FINEST com.mindviewinc.test : FINEST random : FINEST individual loggers set to FINEST -- printing levels -- net : FINEST com.mindviewinc : null -com.mindviewinc.util : FINEST com.mindviewinc.test : FINEST +onjava : FINEST com.mindviewinc.test : FINEST random : FINEST net level: FINEST ___[ Error Output ]___ @@ -88,13 +88,13 @@ printLogMessages SEVERE: com.mindviewinc Severe Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -INFO: com.mindviewinc.util Info +INFO: onjava Info Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -WARNING: com.mindviewinc.util Warning +WARNING: onjava Warning Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -SEVERE: com.mindviewinc.util Severe +SEVERE: onjava Severe Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages INFO: com.mindviewinc.test Info @@ -127,13 +127,13 @@ printLogMessages SEVERE: com.mindviewinc Severe Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -INFO: com.mindviewinc.util Info +INFO: onjava Info Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -WARNING: com.mindviewinc.util Warning +WARNING: onjava Warning Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -SEVERE: com.mindviewinc.util Severe +SEVERE: onjava Severe Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages INFO: com.mindviewinc.test Info @@ -172,13 +172,13 @@ printLogMessages SEVERE: com.mindviewinc Severe Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -INFO: com.mindviewinc.util Info +INFO: onjava Info Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -WARNING: com.mindviewinc.util Warning +WARNING: onjava Warning Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages -SEVERE: com.mindviewinc.util Severe +SEVERE: onjava Severe Jun 15, 2015 3:47:52 PM LoggingLevelManipulation printLogMessages INFO: com.mindviewinc.test Info diff --git a/logging/LoggingLevels.java b/logging/LoggingLevels.java index 233f94b0..2b987e0b 100644 --- a/logging/LoggingLevels.java +++ b/logging/LoggingLevels.java @@ -6,7 +6,7 @@ public class LoggingLevels { private static Logger lgr = Logger.getLogger("com"), lgr2 = Logger.getLogger("com.mindviewinc"), - util= Logger.getLogger("com.mindviewinc.util"), + util= Logger.getLogger("onjava"), test= Logger.getLogger("com.mindviewinc.test"), rand = Logger.getLogger("random"); private static void logMessages() { diff --git a/logging/log.prop b/logging/log.prop index 52251f6b..59f2f7ff 100644 --- a/logging/log.prop +++ b/logging/log.prop @@ -27,6 +27,6 @@ java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter # Set Logger Levels # net.level=SEVERE com.mindviewinc.level = FINEST -com.mindviewinc.util.level = INFO +onjava.level = INFO com.mindviewinc.test.level = FINER random.level= SEVERE diff --git a/network/ChatterClient.java b/network/ChatterClient.java index 549f4338..88c2d5bc 100644 --- a/network/ChatterClient.java +++ b/network/ChatterClient.java @@ -4,7 +4,7 @@ // clients, each of which sends datagrams. import java.net.*; import java.io.*; -import com.mindviewinc.util.*; +import onjava.*; public class ChatterClient extends Thread { // Can listen & send on the same socket: diff --git a/network/ChatterServer.java b/network/ChatterServer.java index f6fa2ba2..ca2a7ad3 100644 --- a/network/ChatterServer.java +++ b/network/ChatterServer.java @@ -3,7 +3,7 @@ // A server that echoes datagrams import java.net.*; import java.io.*; -import com.mindviewinc.util.*; +import onjava.*; public class ChatterServer { static final int INPORT = 1711; diff --git a/network/MultiSimpleClient.java b/network/MultiSimpleClient.java index af169c70..900f1cde 100644 --- a/network/MultiSimpleClient.java +++ b/network/MultiSimpleClient.java @@ -4,7 +4,7 @@ // {ValidateByHand} import java.net.*; import java.io.*; -import com.mindviewinc.util.*; +import onjava.*; class SimpleClientThread extends Thread { private Socket socket; diff --git a/network/MultiSimpleServer.java b/network/MultiSimpleServer.java index 1333aa61..d15bd7c2 100644 --- a/network/MultiSimpleServer.java +++ b/network/MultiSimpleServer.java @@ -4,7 +4,7 @@ // {ValidateByHand} import java.io.*; import java.net.*; -import com.mindviewinc.util.*; +import onjava.*; class ServeOneSimple extends Thread { private Socket socket; diff --git a/objects/HelloDate.java b/objects/HelloDate.java index 7a0152a2..05ecb4e2 100644 --- a/objects/HelloDate.java +++ b/objects/HelloDate.java @@ -2,14 +2,14 @@ import java.util.*; /** The first On Java example program. - * Displays a string and today's date. + * Displays a String and today's date. * @author Bruce Eckel * @author www.MindviewInc.com * @version 5.0 */ public class HelloDate { /** Entry point to class & application. - * @param args array of string arguments + * @param args array of String arguments * @throws exceptions No exceptions thrown */ public static void main(String[] args) { diff --git a/com/mindviewinc/util/BasicSupplier.java b/onjava/BasicSupplier.java similarity index 89% rename from com/mindviewinc/util/BasicSupplier.java rename to onjava/BasicSupplier.java index 5714a6b9..c6d3c28e 100644 --- a/com/mindviewinc/util/BasicSupplier.java +++ b/onjava/BasicSupplier.java @@ -1,7 +1,7 @@ -// com/mindviewinc/util/BasicSupplier.java +// onjava/BasicSupplier.java // Automatically create a Supplier, given a class // with a default (no-arg) constructor. -package com.mindviewinc.util; +package onjava; import java.util.function.*; public class BasicSupplier implements Supplier { diff --git a/com/mindviewinc/util/BinaryFile.java b/onjava/BinaryFile.java similarity index 86% rename from com/mindviewinc/util/BinaryFile.java rename to onjava/BinaryFile.java index 422f7aa8..1e474603 100644 --- a/com/mindviewinc/util/BinaryFile.java +++ b/onjava/BinaryFile.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/BinaryFile.java +// onjava/BinaryFile.java // Utility for reading files in binary form. -package com.mindviewinc.util; +package onjava; import java.io.*; public class BinaryFile { diff --git a/com/mindviewinc/util/CollectionData.java b/onjava/CollectionData.java similarity index 85% rename from com/mindviewinc/util/CollectionData.java rename to onjava/CollectionData.java index f0a4d36a..9dc36daa 100644 --- a/com/mindviewinc/util/CollectionData.java +++ b/onjava/CollectionData.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/CollectionData.java +// onjava/CollectionData.java // A Collection filled with data using a generator object. -package com.mindviewinc.util; +package onjava; import java.util.*; import java.util.function.*; diff --git a/com/mindviewinc/util/ContainerMethodDifferences.java b/onjava/ContainerMethodDifferences.java similarity index 97% rename from com/mindviewinc/util/ContainerMethodDifferences.java rename to onjava/ContainerMethodDifferences.java index e1b63362..37f5a5ce 100644 --- a/com/mindviewinc/util/ContainerMethodDifferences.java +++ b/onjava/ContainerMethodDifferences.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/ContainerMethodDifferences.java -package com.mindviewinc.util; +// onjava/ContainerMethodDifferences.java +package onjava; import java.lang.reflect.*; import java.util.*; diff --git a/com/mindviewinc/util/ConvertTo.java b/onjava/ConvertTo.java similarity index 95% rename from com/mindviewinc/util/ConvertTo.java rename to onjava/ConvertTo.java index 140560e9..1be84c08 100644 --- a/com/mindviewinc/util/ConvertTo.java +++ b/onjava/ConvertTo.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/ConvertTo.java -package com.mindviewinc.util; +// onjava/ConvertTo.java +package onjava; public class ConvertTo { public static boolean[] primitive(Boolean[] in) { diff --git a/com/mindviewinc/util/CountingIntegerList.java b/onjava/CountingIntegerList.java similarity index 87% rename from com/mindviewinc/util/CountingIntegerList.java rename to onjava/CountingIntegerList.java index 8d0cc6a8..bb04d65e 100644 --- a/com/mindviewinc/util/CountingIntegerList.java +++ b/onjava/CountingIntegerList.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/CountingIntegerList.java +// onjava/CountingIntegerList.java // List of any length, containing sample data. -package com.mindviewinc.util; +package onjava; import java.util.*; public class CountingIntegerList diff --git a/com/mindviewinc/util/CountingMapData.java b/onjava/CountingMapData.java similarity index 96% rename from com/mindviewinc/util/CountingMapData.java rename to onjava/CountingMapData.java index caf10ea2..66a54116 100644 --- a/com/mindviewinc/util/CountingMapData.java +++ b/onjava/CountingMapData.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/CountingMapData.java +// onjava/CountingMapData.java // Unlimited-length Map containing sample data. -package com.mindviewinc.util; +package onjava; import java.util.*; public class CountingMapData diff --git a/com/mindviewinc/util/CountingSupplier.java b/onjava/CountingSupplier.java similarity index 96% rename from com/mindviewinc/util/CountingSupplier.java rename to onjava/CountingSupplier.java index 4f1ffbd0..df9af77c 100644 --- a/com/mindviewinc/util/CountingSupplier.java +++ b/onjava/CountingSupplier.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/CountingSupplier.java +// onjava/CountingSupplier.java // Simple generator implementations. -package com.mindviewinc.util; +package onjava; import java.util.function.*; public class CountingSupplier { diff --git a/com/mindviewinc/util/Countries.java b/onjava/Countries.java similarity index 99% rename from com/mindviewinc/util/Countries.java rename to onjava/Countries.java index ee5073b1..ae5a8998 100644 --- a/com/mindviewinc/util/Countries.java +++ b/onjava/Countries.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/Countries.java +// onjava/Countries.java // "Flyweight" Maps and Lists of sample data. -package com.mindviewinc.util; +package onjava; import java.util.*; public class Countries { diff --git a/com/mindviewinc/util/DaemonThreadFactory.java b/onjava/DaemonThreadFactory.java similarity index 73% rename from com/mindviewinc/util/DaemonThreadFactory.java rename to onjava/DaemonThreadFactory.java index 9ab568ba..0bec98ee 100644 --- a/com/mindviewinc/util/DaemonThreadFactory.java +++ b/onjava/DaemonThreadFactory.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/DaemonThreadFactory.java -package com.mindviewinc.util; +// onjava/DaemonThreadFactory.java +package onjava; import java.util.concurrent.*; public class DaemonThreadFactory implements ThreadFactory { diff --git a/com/mindviewinc/util/DaemonThreadPoolExecutor.java b/onjava/DaemonThreadPoolExecutor.java similarity index 75% rename from com/mindviewinc/util/DaemonThreadPoolExecutor.java rename to onjava/DaemonThreadPoolExecutor.java index 63cd2e5f..667c02ff 100644 --- a/com/mindviewinc/util/DaemonThreadPoolExecutor.java +++ b/onjava/DaemonThreadPoolExecutor.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/DaemonThreadPoolExecutor.java -package com.mindviewinc.util; +// onjava/DaemonThreadPoolExecutor.java +package onjava; import java.util.concurrent.*; public class DaemonThreadPoolExecutor diff --git a/com/mindviewinc/util/Deque.java b/onjava/Deque.java similarity index 90% rename from com/mindviewinc/util/Deque.java rename to onjava/Deque.java index 2147c5e8..0061a28e 100644 --- a/com/mindviewinc/util/Deque.java +++ b/onjava/Deque.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/Deque.java +// onjava/Deque.java // Creating a Deque from a LinkedList. -package com.mindviewinc.util; +package onjava; import java.util.*; public class Deque { diff --git a/com/mindviewinc/util/Directory.java b/onjava/Directory.java similarity index 97% rename from com/mindviewinc/util/Directory.java rename to onjava/Directory.java index aadc182e..276fbd6c 100644 --- a/com/mindviewinc/util/Directory.java +++ b/onjava/Directory.java @@ -1,8 +1,8 @@ -// com/mindviewinc/util/Directory.java +// onjava/Directory.java // Produce a sequence of File objects that match a // regular expression in either a local directory, // or by walking a directory tree. -package com.mindviewinc.util; +package onjava; import java.util.regex.*; import java.io.*; import java.util.*; diff --git a/com/mindviewinc/util/Enums.java b/onjava/Enums.java similarity index 81% rename from com/mindviewinc/util/Enums.java rename to onjava/Enums.java index 5555c7ad..0c89da48 100644 --- a/com/mindviewinc/util/Enums.java +++ b/onjava/Enums.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/Enums.java -package com.mindviewinc.util; +// onjava/Enums.java +package onjava; import java.util.*; public class Enums { diff --git a/com/mindviewinc/util/Generated.java b/onjava/Generated.java similarity index 87% rename from com/mindviewinc/util/Generated.java rename to onjava/Generated.java index a3d2c5fd..7db3ffdf 100644 --- a/com/mindviewinc/util/Generated.java +++ b/onjava/Generated.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/Generated.java -package com.mindviewinc.util; +// onjava/Generated.java +package onjava; import java.util.function.*; public class Generated { diff --git a/com/mindviewinc/util/Hex.java b/onjava/Hex.java similarity index 80% rename from com/mindviewinc/util/Hex.java rename to onjava/Hex.java index 3b8a68ef..507ac5e2 100644 --- a/com/mindviewinc/util/Hex.java +++ b/onjava/Hex.java @@ -1,6 +1,7 @@ -// com/mindviewinc/util/Hex.java -package com.mindviewinc.util; +// onjava/Hex.java +package onjava; import java.io.*; +import java.nio.file.*; public class Hex { public static String format(byte[] data) { @@ -19,11 +20,11 @@ public class Hex { public static void main(String[] args) throws Exception { if(args.length == 0) // Test by displaying this class file: - System.out.println( - format(BinaryFile.read("Hex.class"))); + System.out.println(format( + Files.readAllBytes(Paths.get("Hex.class")))); else - System.out.println( - format(BinaryFile.read(new File(args[0])))); + System.out.println(format( + Files.readAllBytes(Paths.get(args[0])))); } } /* Output: (First 6 Lines) diff --git a/com/mindviewinc/util/MapData.java b/onjava/MapData.java similarity index 96% rename from com/mindviewinc/util/MapData.java rename to onjava/MapData.java index 95581fc3..a0043ca7 100644 --- a/com/mindviewinc/util/MapData.java +++ b/onjava/MapData.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/MapData.java +// onjava/MapData.java // A Map filled with data using a generator object. -package com.mindviewinc.util; +package onjava; import java.util.*; import java.util.function.*; diff --git a/com/mindviewinc/util/MouseClick.java b/onjava/MouseClick.java similarity index 86% rename from com/mindviewinc/util/MouseClick.java rename to onjava/MouseClick.java index 1354dd3b..ce78525f 100644 --- a/com/mindviewinc/util/MouseClick.java +++ b/onjava/MouseClick.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/MouseClick.java +// onjava/MouseClick.java // Helper interface to allow lambda expressions -package com.mindviewinc.util; +package onjava; import java.awt.event.*; // Default everything except mouseClicked(): diff --git a/onjava/Null.java b/onjava/Null.java new file mode 100644 index 00000000..3d271425 --- /dev/null +++ b/onjava/Null.java @@ -0,0 +1,3 @@ +// onjava/Null.java +package onjava; +public interface Null {} diff --git a/com/mindviewinc/util/OSExecute.java b/onjava/OSExecute.java similarity index 94% rename from com/mindviewinc/util/OSExecute.java rename to onjava/OSExecute.java index a1c0a2fc..3d877b80 100644 --- a/com/mindviewinc/util/OSExecute.java +++ b/onjava/OSExecute.java @@ -1,7 +1,7 @@ -// com/mindviewinc/util/OSExecute.java +// onjava/OSExecute.java // Run an operating system command // and send the output to the console. -package com.mindviewinc.util; +package onjava; import java.io.*; public class OSExecute { diff --git a/com/mindviewinc/util/OSExecuteException.java b/onjava/OSExecuteException.java similarity index 60% rename from com/mindviewinc/util/OSExecuteException.java rename to onjava/OSExecuteException.java index 2d3e8753..344c4e7c 100644 --- a/com/mindviewinc/util/OSExecuteException.java +++ b/onjava/OSExecuteException.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/OSExecuteException.java -package com.mindviewinc.util; +// onjava/OSExecuteException.java +package onjava; public class OSExecuteException extends RuntimeException { public OSExecuteException(String why) { super(why); } diff --git a/com/mindviewinc/util/PPrint.java b/onjava/PPrint.java similarity index 90% rename from com/mindviewinc/util/PPrint.java rename to onjava/PPrint.java index bd7e1998..7f53ec33 100644 --- a/com/mindviewinc/util/PPrint.java +++ b/onjava/PPrint.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/PPrint.java +// onjava/PPrint.java // Pretty-printer for collections -package com.mindviewinc.util; +package onjava; import java.util.*; public class PPrint { diff --git a/com/mindviewinc/util/Pair.java b/onjava/Pair.java similarity index 67% rename from com/mindviewinc/util/Pair.java rename to onjava/Pair.java index 2ecfa463..40263838 100644 --- a/com/mindviewinc/util/Pair.java +++ b/onjava/Pair.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/Pair.java -package com.mindviewinc.util; +// onjava/Pair.java +package onjava; public class Pair { public final K key; diff --git a/com/mindviewinc/util/ProcessFiles.java b/onjava/ProcessFiles.java similarity index 94% rename from com/mindviewinc/util/ProcessFiles.java rename to onjava/ProcessFiles.java index 402e9af8..8771cd16 100644 --- a/com/mindviewinc/util/ProcessFiles.java +++ b/onjava/ProcessFiles.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/ProcessFiles.java +// onjava/ProcessFiles.java // {ValidateByHand} -package com.mindviewinc.util; +package onjava; import java.io.*; public class ProcessFiles { diff --git a/com/mindviewinc/util/RandomSupplier.java b/onjava/RandomSupplier.java similarity index 96% rename from com/mindviewinc/util/RandomSupplier.java rename to onjava/RandomSupplier.java index 230b2683..73e78d98 100644 --- a/com/mindviewinc/util/RandomSupplier.java +++ b/onjava/RandomSupplier.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/RandomSupplier.java +// onjava/RandomSupplier.java // Suppliers that produce random values. -package com.mindviewinc.util; +package onjava; import java.util.*; import java.util.function.*; diff --git a/com/mindviewinc/util/Range.java b/onjava/Range.java similarity index 92% rename from com/mindviewinc/util/Range.java rename to onjava/Range.java index ecffa1d7..cb33ca8c 100644 --- a/com/mindviewinc/util/Range.java +++ b/onjava/Range.java @@ -1,7 +1,7 @@ -// com/mindviewinc/util/Range.java +// onjava/Range.java // Array creation methods that can be used without // qualifiers, using static imports: -package com.mindviewinc.util; +package onjava; public class Range { // Produce a sequence [0..n) diff --git a/onjava/Repeat.java b/onjava/Repeat.java new file mode 100644 index 00000000..4e49d47f --- /dev/null +++ b/onjava/Repeat.java @@ -0,0 +1,9 @@ +// onjava/Repeat.java +package onjava; +import static java.util.stream.IntStream.*; + +public class Repeat { + public static void repeat(int n, Runnable action) { + range(0, n).forEach(i -> action.run()); + } +} diff --git a/com/mindviewinc/util/Sets.java b/onjava/Sets.java similarity index 91% rename from com/mindviewinc/util/Sets.java rename to onjava/Sets.java index baf75f2b..dd87b7a1 100644 --- a/com/mindviewinc/util/Sets.java +++ b/onjava/Sets.java @@ -1,5 +1,5 @@ -// com/mindviewinc/util/Sets.java -package com.mindviewinc.util; +// onjava/Sets.java +package onjava; import java.util.*; public class Sets { diff --git a/com/mindviewinc/util/Sleep.java b/onjava/Sleep.java similarity index 78% rename from com/mindviewinc/util/Sleep.java rename to onjava/Sleep.java index 721b20bf..ae78db91 100644 --- a/com/mindviewinc/util/Sleep.java +++ b/onjava/Sleep.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/Sleep.java +// onjava/Sleep.java // Sleep for n seconds. -package com.mindviewinc.util; +package onjava; import java.util.concurrent.*; public class Sleep { diff --git a/com/mindviewinc/util/Stack.java b/onjava/Stack.java similarity index 86% rename from com/mindviewinc/util/Stack.java rename to onjava/Stack.java index 0744ea33..99e8e3d9 100644 --- a/com/mindviewinc/util/Stack.java +++ b/onjava/Stack.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/Stack.java +// onjava/Stack.java // Making a stack from a LinkedList. -package com.mindviewinc.util; +package onjava; import java.util.LinkedList; public class Stack { diff --git a/com/mindviewinc/util/SwingConsole.java b/onjava/SwingConsole.java similarity index 85% rename from com/mindviewinc/util/SwingConsole.java rename to onjava/SwingConsole.java index b695f335..2a3b07dd 100644 --- a/com/mindviewinc/util/SwingConsole.java +++ b/onjava/SwingConsole.java @@ -1,7 +1,7 @@ -// com/mindviewinc/util/SwingConsole.java +// onjava/SwingConsole.java // Tool for running Swing demos from the // console, both applets and JFrames. -package com.mindviewinc.util; +package onjava; import javax.swing.*; public class SwingConsole { diff --git a/com/mindviewinc/util/TaskItem.java b/onjava/TaskItem.java similarity index 80% rename from com/mindviewinc/util/TaskItem.java rename to onjava/TaskItem.java index 36881c09..56e9bc5f 100644 --- a/com/mindviewinc/util/TaskItem.java +++ b/onjava/TaskItem.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/TaskItem.java +// onjava/TaskItem.java // A Future and the Callable that produced it. -package com.mindviewinc.util; +package onjava; import java.util.concurrent.*; public class TaskItem> { diff --git a/com/mindviewinc/util/TaskManager.java b/onjava/TaskManager.java similarity index 94% rename from com/mindviewinc/util/TaskManager.java rename to onjava/TaskManager.java index 73ef9a67..95e1ce0b 100644 --- a/com/mindviewinc/util/TaskManager.java +++ b/onjava/TaskManager.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/TaskManager.java +// onjava/TaskManager.java // Managing and executing a queue of tasks. -package com.mindviewinc.util; +package onjava; import java.util.concurrent.*; import java.util.*; diff --git a/com/mindviewinc/util/TextFile.java b/onjava/TextFile.java similarity index 93% rename from com/mindviewinc/util/TextFile.java rename to onjava/TextFile.java index 3141b9a9..6612959b 100644 --- a/com/mindviewinc/util/TextFile.java +++ b/onjava/TextFile.java @@ -1,12 +1,12 @@ -// com/mindviewinc/util/TextFile.java +// onjava/TextFile.java // Static functions for reading and writing text files as -// a single string, and treating a file as an ArrayList. -package com.mindviewinc.util; +// a single String, and treating a file as an ArrayList. +package onjava; import java.io.*; import java.util.*; public class TextFile extends ArrayList { - // Read a file as a single string: + // Read a file as a single String: public static String read(String fileName) { StringBuilder sb = new StringBuilder(); try { diff --git a/com/mindviewinc/util/TimedAbort.java b/onjava/TimedAbort.java similarity index 81% rename from com/mindviewinc/util/TimedAbort.java rename to onjava/TimedAbort.java index adfa1d28..51d2ed73 100644 --- a/com/mindviewinc/util/TimedAbort.java +++ b/onjava/TimedAbort.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/TimedAbort.java +// onjava/TimedAbort.java // Terminate a program after n seconds. -package com.mindviewinc.util; +package onjava; import java.util.*; public class TimedAbort { diff --git a/onjava/Tuple.java b/onjava/Tuple.java new file mode 100644 index 00000000..fe38b16a --- /dev/null +++ b/onjava/Tuple.java @@ -0,0 +1,21 @@ +// onjava/Tuple.java +// Tuple library using type argument inference. +package onjava; + +public class Tuple { + public static Tuple2 tuple(A a, B b) { + return new Tuple2<>(a, b); + } + public static Tuple3 + tuple(A a, B b, C c) { + return new Tuple3<>(a, b, c); + } + public static Tuple4 + tuple(A a, B b, C c, D d) { + return new Tuple4<>(a, b, c, d); + } + public static + Tuple5 tuple(A a, B b, C c, D d, E e) { + return new Tuple5<>(a, b, c, d, e); + } +} diff --git a/onjava/Tuple2.java b/onjava/Tuple2.java new file mode 100644 index 00000000..d11e8b2d --- /dev/null +++ b/onjava/Tuple2.java @@ -0,0 +1,13 @@ +// onjava/Tuple2.java +package onjava; + +public class Tuple2 { + public final A _1; + public final B _2; + public Tuple2(A a, B b) { _1 = a; _2 = b; } + public String rep() { return _1 + ", " + _2; } + @Override + public String toString() { + return "(" + rep() + ")"; + } +} diff --git a/onjava/Tuple3.java b/onjava/Tuple3.java new file mode 100644 index 00000000..91d508dd --- /dev/null +++ b/onjava/Tuple3.java @@ -0,0 +1,14 @@ +// onjava/Tuple3.java +package onjava; + +public class Tuple3 extends Tuple2 { + public final C _3; + public Tuple3(A a, B b, C c) { + super(a, b); + _3 = c; + } + @Override + public String rep() { + return super.rep() + ", " + _3; + } +} diff --git a/onjava/Tuple4.java b/onjava/Tuple4.java new file mode 100644 index 00000000..149ca4f8 --- /dev/null +++ b/onjava/Tuple4.java @@ -0,0 +1,15 @@ +// onjava/Tuple4.java +package onjava; + +public class Tuple4 + extends Tuple3 { + public final D _4; + public Tuple4(A a, B b, C c, D d) { + super(a, b, c); + _4 = d; + } + @Override + public String rep() { + return super.rep() + ", " + _4; + } +} diff --git a/onjava/Tuple5.java b/onjava/Tuple5.java new file mode 100644 index 00000000..8b14e020 --- /dev/null +++ b/onjava/Tuple5.java @@ -0,0 +1,15 @@ +// onjava/Tuple5.java +package onjava; + +public class Tuple5 +extends Tuple4 { + public final E _5; + public Tuple5(A a, B b, C c, D d, E e) { + super(a, b, c, d); + _5 = e; + } + @Override + public String rep() { + return super.rep() + ", " + _5; + } +} diff --git a/com/mindviewinc/util/TypeCounter.java b/onjava/TypeCounter.java similarity index 94% rename from com/mindviewinc/util/TypeCounter.java rename to onjava/TypeCounter.java index 76255dda..a4f6dc66 100644 --- a/com/mindviewinc/util/TypeCounter.java +++ b/onjava/TypeCounter.java @@ -1,6 +1,6 @@ -// com/mindviewinc/util/TypeCounter.java +// onjava/TypeCounter.java // Counts instances of a type family. -package com.mindviewinc.util; +package onjava; import java.util.*; public class TypeCounter extends HashMap,Integer>{ diff --git a/onjava/build.xml b/onjava/build.xml new file mode 100644 index 00000000..371f1f24 --- /dev/null +++ b/onjava/build.xml @@ -0,0 +1,19 @@ + + + + + + + + + + + + + + + + + + + diff --git a/operators/HelloDate.java b/operators/HelloDate.java deleted file mode 100644 index fdc154c1..00000000 --- a/operators/HelloDate.java +++ /dev/null @@ -1,13 +0,0 @@ -// operators/HelloDate.java -import java.util.*; - -public class HelloDate { - public static void main(String[] args) { - System.out.println("Hello, it's: "); - System.out.println(new Date()); - } -} -/* Output: -Hello, it's: -Mon Jun 15 15:47:53 PDT 2015 -*/ diff --git a/operators/build.xml b/operators/build.xml index 5282f175..dd288cd3 100644 --- a/operators/build.xml +++ b/operators/build.xml @@ -17,7 +17,6 @@ - diff --git a/patterns/PaperScissorsRock.java b/patterns/PaperScissorsRock.java index aca769a6..8b83a420 100644 --- a/patterns/PaperScissorsRock.java +++ b/patterns/PaperScissorsRock.java @@ -3,6 +3,8 @@ import java.util.*; import java.util.function.*; import java.util.stream.*; +import onjava.*; +import static onjava.Tuple.*; enum Outcome { WIN, LOSE, DRAW } @@ -76,15 +78,6 @@ class Rock implements Item { public String toString() { return "Rock"; } } -class ItemPair { - Item first; - Item second; - ItemPair(Item f, Item s) { - first = f; - second = s; - } -} - class ItemFactory { static List> items = Arrays.asList( @@ -94,16 +87,15 @@ class ItemFactory { public static Item newItem() { return items.get(rand.nextInt(sz)).get(); } - public static ItemPair newPair() { - return new ItemPair(newItem(), newItem()); + public static Tuple2 newPair() { + return tuple(newItem(), newItem()); } } class Compete { - public static Outcome match(ItemPair p) { - System.out.print( - p.first + " <--> " + p.second + " : "); - return p.first.compete(p.second); + public static Outcome match(Tuple2 p) { + System.out.print(p._1 + " -> " + p._2 + " : "); + return p._1.compete(p._2); } } diff --git a/patterns/visitor/BeeAndFlowers.java b/patterns/visitor/BeeAndFlowers.java index dfe56db2..7e71a27a 100644 --- a/patterns/visitor/BeeAndFlowers.java +++ b/patterns/visitor/BeeAndFlowers.java @@ -31,7 +31,7 @@ class Chrysanthemum implements Flower { public void accept(Visitor v) { v.visit(this);} } -// Add the ability to produce a string: +// Add the ability to produce a String: class StringVal implements Visitor { String s; @Override diff --git a/patterns/visualobserver/BoxObserver.java b/patterns/visualobserver/BoxObserver.java index bc9c6928..6c7df483 100644 --- a/patterns/visualobserver/BoxObserver.java +++ b/patterns/visualobserver/BoxObserver.java @@ -7,7 +7,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; -import com.mindviewinc.util.MouseClick; +import onjava.MouseClick; // You must inherit a new type of Observable: class BoxObservable extends Observable { diff --git a/xml/APerson.java b/serialization/APerson.java similarity index 98% rename from xml/APerson.java rename to serialization/APerson.java index 07b00eee..0c7c8e8a 100644 --- a/xml/APerson.java +++ b/serialization/APerson.java @@ -1,4 +1,4 @@ -// xml/APerson.java +// serialization/APerson.java // Use the XOM library to write and read XML // {Requires: nu.xom.Node; You must install // the XOM library from http://www.xom.nu } diff --git a/xml/People.java b/serialization/People.java similarity index 96% rename from xml/People.java rename to serialization/People.java index 2b7ac239..48590db1 100644 --- a/xml/People.java +++ b/serialization/People.java @@ -1,4 +1,4 @@ -// xml/People.java +// serialization/People.java // {Requires: nu.xom.Node; You must install // the XOM library from http://www.xom.nu } // {RunFirst: APerson} diff --git a/serialization/build.xml b/serialization/build.xml index cb08bf6c..d79fc7ef 100644 --- a/serialization/build.xml +++ b/serialization/build.xml @@ -7,12 +7,14 @@ + + diff --git a/standardio/OSExecuteDemo.java b/standardio/OSExecuteDemo.java index 63270d34..7c7a3ccc 100644 --- a/standardio/OSExecuteDemo.java +++ b/standardio/OSExecuteDemo.java @@ -1,6 +1,6 @@ // standardio/OSExecuteDemo.java // Demonstrates standard I/O redirection. -import com.mindviewinc.util.*; +import onjava.*; public class OSExecuteDemo { public static void main(String[] args) { diff --git a/streams/AnImplementation.java b/streams/AnImplementation.java new file mode 100644 index 00000000..bcdc6174 --- /dev/null +++ b/streams/AnImplementation.java @@ -0,0 +1,19 @@ +// streams/AnImplementation.java + +public class AnImplementation implements AnInterface { + public void firstMethod() { + System.out.println("firstMethod"); + } + public void secondMethod() { + System.out.println("secondMethod"); + } + public static void main(String[] args) { + AnInterface i = new AnImplementation(); + i.firstMethod(); + i.secondMethod(); + } +} +/* Output: +firstMethod +secondMethod +*/ diff --git a/streams/AnInterface.java b/streams/AnInterface.java new file mode 100644 index 00000000..765de609 --- /dev/null +++ b/streams/AnInterface.java @@ -0,0 +1,6 @@ +// streams/AnInterface.java + +interface AnInterface { + void firstMethod(); + void secondMethod(); +} diff --git a/streams/ArrayStreams.java b/streams/ArrayStreams.java new file mode 100644 index 00000000..91c6c45e --- /dev/null +++ b/streams/ArrayStreams.java @@ -0,0 +1,37 @@ +// streams/ArrayStreams.java +import java.util.*; +import java.util.stream.*; + +public class ArrayStreams { + public static void main(String[] args) { + Arrays.stream(new double[] { 3.14159, 2.718, 1.618 }) + .forEach(System.out::println); + Arrays.stream(new int[] { 1, 3, 5 }) + .forEach(System.out::println); + Arrays.stream(new long[] { 11, 22, 44, 66 }) + .forEach(System.out::println); + // Select a subrange: + Arrays.stream( + new int[] { 1, 3, 5, 7, 15, 28, 37 }, 3, 6) + .forEach(System.out::println); + } +} +/* Output: +3.14159 +2.718 +1.618 +1 +3 +5 +7 +15 +28 +37 +11 +22 +44 +66 +7 +15 +28 +*/ diff --git a/streams/Bubble.java b/streams/Bubble.java new file mode 100644 index 00000000..d684effa --- /dev/null +++ b/streams/Bubble.java @@ -0,0 +1,19 @@ +// streams/Bubble.java +import java.util.function.*; + +public class Bubble { + public final int i; + public Bubble(int n) { i = n; } + @Override + public String toString() { + return "Bubble(" + i + ")"; + } + private static + class BubbleFactory implements Supplier { + private static int count = 0; + @Override + public Bubble get() { return new Bubble(count++); } + } + public static final + BubbleFactory factory = new BubbleFactory(); +} diff --git a/streams/Bubbles.java b/streams/Bubbles.java new file mode 100644 index 00000000..3d75bd4a --- /dev/null +++ b/streams/Bubbles.java @@ -0,0 +1,22 @@ +// streams/Bubbles.java +import java.util.stream.*; + +public class Bubbles { + public static void main(String[] args) { + Stream.generate(Bubble.factory) + .limit(10) + .forEach(System.out::println); + } +} +/* Output: +Bubble(0) +Bubble(1) +Bubble(2) +Bubble(3) +Bubble(4) +Bubble(5) +Bubble(6) +Bubble(7) +Bubble(8) +Bubble(9) +*/ diff --git a/streams/Cheese.dat b/streams/Cheese.dat new file mode 100644 index 00000000..936666ed --- /dev/null +++ b/streams/Cheese.dat @@ -0,0 +1,6 @@ +// streams/Cheese.dat +Not much of a cheese shop really, is it? +Finest in the district, sir. +And what leads you to that conclusion? +Well, it's so clean. +It's certainly uncontaminated by cheese. diff --git a/streams/CollectionToStream.java b/streams/CollectionToStream.java new file mode 100644 index 00000000..5d5f39fb --- /dev/null +++ b/streams/CollectionToStream.java @@ -0,0 +1,36 @@ +// streams/CollectionToStream.java +import java.util.*; +import java.util.stream.*; + +public class CollectionToStream { + public static void main(String[] args) { + List bubbles = Arrays.asList( + new Bubble(1), new Bubble(2), new Bubble(3)); + System.out.println( + bubbles.stream() + .mapToInt(b -> b.i) + .sum()); + + Set w = new HashSet<>(Arrays.asList( + "It's a wonderful day for pie!".split(" "))); + w.stream() + .map(x -> x + " ") + .forEach(System.out::print); + System.out.println(); + + Map m = new HashMap<>(); + m.put("pi", 3.14159); + m.put("e", 2.718); + m.put("phi", 1.618); + m.entrySet().stream() + .map(e -> e.getKey() + ": " + e.getValue()) + .forEach(System.out::println); + } +} +/* Output: +6 +a pie! It's for wonderful day +phi: 1.618 +e: 2.718 +pi: 3.14159 +*/ diff --git a/streams/CreatingOptionals.java b/streams/CreatingOptionals.java new file mode 100644 index 00000000..9a23c8f3 --- /dev/null +++ b/streams/CreatingOptionals.java @@ -0,0 +1,34 @@ +// streams/CreatingOptionals.java +import java.util.*; +import java.util.stream.*; +import java.util.function.*; + +class CreatingOptionals { + static void + test(String testName, Optional opt) { + System.out.println(" === " + testName + " === "); + System.out.println(opt.orElse("Null")); + } + public static void main(String[] args) { + test("empty", Optional.empty()); + test("of", Optional.of("Howdy")); + try { + test("of", Optional.of(null)); + } catch(Exception e) { + System.out.println(e); + } + test("ofNullable", Optional.ofNullable("Hi")); + test("ofNullable", Optional.ofNullable(null)); + } +} +/* Output: + === empty === +Null + === of === +Howdy +java.lang.NullPointerException + === ofNullable === +Hi + === ofNullable === +Null +*/ diff --git a/streams/Duplicator.java b/streams/Duplicator.java new file mode 100644 index 00000000..11d65b3e --- /dev/null +++ b/streams/Duplicator.java @@ -0,0 +1,15 @@ +// streams/Duplicator.java +import java.util.stream.*; + +public class Duplicator { + public static void main(String[] args) { + Stream.generate(() -> "duplicate") + .limit(3) + .forEach(System.out::println); + } +} +/* Output: +duplicate +duplicate +duplicate +*/ diff --git a/streams/Fibonacci.java b/streams/Fibonacci.java new file mode 100644 index 00000000..b7b937a4 --- /dev/null +++ b/streams/Fibonacci.java @@ -0,0 +1,31 @@ +// streams/Fibonacci.java +import java.util.stream.*; + +public class Fibonacci { + int x = 1; + Stream numbers() { + return Stream.iterate(0, i -> { + int result = x + i; + x = i; + return result; + }); + } + public static void main(String[] args) { + new Fibonacci().numbers() + .skip(20) // Don't use the first 20 + .limit(10) // Then take 10 of them + .forEach(System.out::println); + } +} +/* Output: +6765 +10946 +17711 +28657 +46368 +75025 +121393 +196418 +317811 +514229 +*/ diff --git a/streams/FileToWords.java b/streams/FileToWords.java new file mode 100644 index 00000000..b0f289f0 --- /dev/null +++ b/streams/FileToWords.java @@ -0,0 +1,14 @@ +// streams/FileToWords.java +import java.nio.file.*; +import java.util.stream.*; +import java.util.regex.Pattern; + +public class FileToWords { + public static Stream stream(String filePath) + throws Exception { + return Files.lines(Paths.get(filePath)) + .skip(1) // First (comment) line + .flatMap(line -> + Pattern.compile("[ .,?]+").splitAsStream(line)); + } +} diff --git a/streams/FileToWordsBuilder.java b/streams/FileToWordsBuilder.java new file mode 100644 index 00000000..84e38300 --- /dev/null +++ b/streams/FileToWordsBuilder.java @@ -0,0 +1,27 @@ +// streams/FileToWordsBuilder.java +import java.io.*; +import java.nio.file.*; +import java.util.stream.*; + +public class FileToWordsBuilder { + Stream.Builder builder = Stream.builder(); + public FileToWordsBuilder(String filePath) + throws Exception { + Files.lines(Paths.get(filePath)) + .skip(1) // Skip the comment line at the beginning + .forEach(line -> { + for(String w : line.split("[ .?,]+")) + builder.add(w); + }); + } + Stream stream() { return builder.build(); } + public static void main(String[] args) throws Exception { + new FileToWordsBuilder("Cheese.dat").stream() + .limit(7) + .map(w -> w + " ") + .forEach(System.out::print); + } +} +/* Output: +Not much of a cheese shop really +*/ diff --git a/streams/FileToWordsRegexp.java b/streams/FileToWordsRegexp.java new file mode 100644 index 00000000..2e63cdc0 --- /dev/null +++ b/streams/FileToWordsRegexp.java @@ -0,0 +1,34 @@ +// streams/FileToWordsRegexp.java +import java.io.*; +import java.nio.file.*; +import java.util.stream.*; +import java.util.regex.Pattern; + +public class FileToWordsRegexp { + private String all; + public FileToWordsRegexp(String filePath) + throws Exception { + all = Files.lines(Paths.get(filePath)) + .skip(1) // First (comment) line + .collect(Collectors.joining(" ")); + } + public Stream stream() { + return Pattern.compile("[ .,?]+").splitAsStream(all); + } + public static void main(String[] args) throws Exception { + FileToWordsRegexp fw = + new FileToWordsRegexp("Cheese.dat"); + fw.stream() + .limit(7) + .map(w -> w + " ") + .forEach(System.out::print); + fw.stream() + .skip(7) + .limit(2) + .map(w -> w + " ") + .forEach(System.out::print); + } +} +/* Output: +Not much of a cheese shop really is it +*/ diff --git a/streams/FileToWordsTest.java b/streams/FileToWordsTest.java new file mode 100644 index 00000000..162bd92b --- /dev/null +++ b/streams/FileToWordsTest.java @@ -0,0 +1,19 @@ +// streams/FileToWordsTest.java +import java.util.stream.*; + +public class FileToWordsTest { + public static void main(String[] args) throws Exception { + FileToWords.stream("Cheese.dat") + .limit(7) + .forEach(s -> System.out.format("%s ", s)); + System.out.println(); + FileToWords.stream("Cheese.dat") + .skip(7) + .limit(2) + .forEach(s -> System.out.format("%s ", s)); + } +} +/* Output: +Not much of a cheese shop really +is it +*/ diff --git a/streams/FlatMap.java b/streams/FlatMap.java new file mode 100644 index 00000000..d02c8578 --- /dev/null +++ b/streams/FlatMap.java @@ -0,0 +1,21 @@ +// streams/FlatMap.java +import java.util.stream.*; + +public class FlatMap { + public static void main(String[] args) { + Stream.of(1, 2, 3) + .flatMap(i -> Stream.of("Gonzo", "Fozzie", "Beaker")) + .forEach(System.out::println); + } +} +/* Output: +Gonzo +Fozzie +Beaker +Gonzo +Fozzie +Beaker +Gonzo +Fozzie +Beaker +*/ diff --git a/streams/ForEach.java b/streams/ForEach.java new file mode 100644 index 00000000..3a8c61f4 --- /dev/null +++ b/streams/ForEach.java @@ -0,0 +1,41 @@ +// streams/ForEach.java +import java.util.*; +import java.util.stream.*; +import static streams.RandInts.*; + +public class ForEach { + final static int sz = 5; + public static void main(String[] args) { + rands().limit(sz) + .forEach(System.out::println); + + System.out.println(" -----"); + rands().limit(sz) + .parallel() + .forEach(System.out::println); + + System.out.println(" -----"); + rands().limit(sz) + .parallel() + .forEachOrdered(System.out::println); + } +} +/* Output: +258 +555 +693 +861 +961 + ----- +861 +961 +258 +693 +555 + ----- +258 +555 +693 +861 +961 +*/ diff --git a/streams/FunctionMap.java b/streams/FunctionMap.java new file mode 100644 index 00000000..7237b435 --- /dev/null +++ b/streams/FunctionMap.java @@ -0,0 +1,57 @@ +// streams/FunctionMap.java +import java.util.*; +import java.util.stream.*; +import java.util.function.*; + +class FunctionMap { + static String[] elements = { "12", "", "23", "45" }; + static Stream testStream() { + return Arrays.stream(elements); + } + static void + test(String descr, Function func) { + System.out.println(" ---( " + descr + " )---"); + testStream() + .map(func) + .forEach(System.out::println); + } + public static void main(String[] args) { + + test("add brackets", s -> "[" + s + "]"); + + test("Increment", s -> { + try { + return Integer.parseInt(s) + 1 + ""; + } catch(NumberFormatException e) { + return s; + } + }); + + test("Replace", s -> s.replace("2", "9")); + + test("Take last digit", s -> s.length() > 0 ? + s.charAt(s.length() - 1) + "" : s); + } +} +/* Output: + ---( add brackets )--- +[12] +[] +[23] +[45] + ---( Increment )--- +13 + +24 +46 + ---( Replace )--- +19 + +93 +45 + ---( Take last digit )--- +2 + +3 +5 +*/ diff --git a/streams/FunctionMap2.java b/streams/FunctionMap2.java new file mode 100644 index 00000000..170f6d5f --- /dev/null +++ b/streams/FunctionMap2.java @@ -0,0 +1,29 @@ +// streams/FunctionMap2.java +// Different input and output types +import java.util.*; +import java.util.stream.*; + +class Numbered { + final int n; + Numbered(int n) { this.n = n; } + @Override + public String toString() { + return "Numbered(" + n + ")"; + } +} + +class FunctionMap2 { + public static void main(String[] args) { + Stream.of(1, 5, 7, 9, 11, 13) + .map(Numbered::new) + .forEach(System.out::println); + } +} +/* Output: +Numbered(1) +Numbered(5) +Numbered(7) +Numbered(9) +Numbered(11) +Numbered(13) +*/ diff --git a/streams/FunctionMap3.java b/streams/FunctionMap3.java new file mode 100644 index 00000000..9ced4c8e --- /dev/null +++ b/streams/FunctionMap3.java @@ -0,0 +1,29 @@ +// streams/FunctionMap3.java +// Producing numeric output streams +import java.util.*; +import java.util.stream.*; + +class FunctionMap3 { + public static void main(String[] args) { + Stream.of("5", "7", "9") + .mapToInt(Integer::parseInt) + .forEach(System.out::println); + Stream.of("17", "19", "23") + .mapToLong(Long::parseLong) + .forEach(System.out::println); + Stream.of("17", "1.9", ".23") + .mapToDouble(Double::parseDouble) + .forEach(System.out::println); + } +} +/* Output: +5 +7 +9 +17 +19 +23 +17.0 +1.9 +0.23 +*/ diff --git a/streams/Generator.java b/streams/Generator.java new file mode 100644 index 00000000..d5db4edf --- /dev/null +++ b/streams/Generator.java @@ -0,0 +1,22 @@ +// streams/Generator.java +import java.util.*; +import java.util.function.*; +import java.util.stream.*; + +public class Generator implements Supplier { + Random rand = new Random(47); + char[] letters = + "ABCDEFGHIJKLMNOPQRSTUVWXYZ".toCharArray(); + public String get() { + return "" + letters[rand.nextInt(letters.length)]; + } + public static void main(String[] args) { + String word = Stream.generate(new Generator()) + .limit(30) + .collect(Collectors.joining()); + System.out.println(word); + } +} +/* Output: +YNZBRNYGCFOWZNTCQRGSEGZMMJMROE +*/ diff --git a/streams/ImperativeRandoms.java b/streams/ImperativeRandoms.java new file mode 100644 index 00000000..1ee54de5 --- /dev/null +++ b/streams/ImperativeRandoms.java @@ -0,0 +1,18 @@ +// streams/ImperativeRandoms.java +import java.util.*; + +public class ImperativeRandoms { + public static void main(String[] args) { + Random rand = new Random(47); + SortedSet rints = new TreeSet<>(); + while(rints.size() < 7) { + int r = rand.nextInt(20); + if(r < 5) continue; + rints.add(r); + } + System.out.println(rints); + } +} +/* Output: +[7, 8, 9, 11, 13, 15, 18] +*/ diff --git a/streams/Implementation2.java b/streams/Implementation2.java new file mode 100644 index 00000000..5a0aad3d --- /dev/null +++ b/streams/Implementation2.java @@ -0,0 +1,23 @@ +// streams/Implementation2.java + +public class Implementation2 +implements InterfaceWithDefault { + public void firstMethod() { + System.out.println("firstMethod"); + } + public void secondMethod() { + System.out.println("secondMethod"); + } + public static void main(String[] args) { + InterfaceWithDefault i = + new Implementation2(); + i.firstMethod(); + i.secondMethod(); + i.newMethod(); + } +} +/* Output: +firstMethod +secondMethod +newMethod +*/ diff --git a/streams/InterfaceWithDefault.java b/streams/InterfaceWithDefault.java new file mode 100644 index 00000000..0bcd316d --- /dev/null +++ b/streams/InterfaceWithDefault.java @@ -0,0 +1,9 @@ +// streams/InterfaceWithDefault.java + +interface InterfaceWithDefault { + void firstMethod(); + void secondMethod(); + default void newMethod() { + System.out.println("newMethod"); + } +} diff --git a/streams/Jim.java b/streams/Jim.java new file mode 100644 index 00000000..1287eef7 --- /dev/null +++ b/streams/Jim.java @@ -0,0 +1,21 @@ +// streams/Jim.java +import java.util.*; + +interface Jim1 { + default void jim() { System.out.println("Jim1::jim"); } +} + +interface Jim2 { + default void jim() { System.out.println("Jim2::jim"); } +} + +public class Jim implements Jim1, Jim2 { + @Override + public void jim() { Jim2.super.jim(); } + public static void main(String[] args) { + new Jim().jim(); + } +} +/* Output: +Jim2::jim +*/ diff --git a/streams/LastElement.java b/streams/LastElement.java new file mode 100644 index 00000000..b6dca9dd --- /dev/null +++ b/streams/LastElement.java @@ -0,0 +1,19 @@ +// streams/LastElement.java +import java.util.*; +import java.util.stream.*; + +public class LastElement { + public static void main(String[] args) { + OptionalInt last = IntStream.range(10, 20) + .reduce((n1, n2) -> n2); + System.out.println(last.orElse(-1)); + // Non-numeric object: + Optional lastobj = Stream.of("one", "two", "three") + .reduce((n1, n2) -> n2); + System.out.println(lastobj.orElse("Nothing there!")); + } +} +/* Output: +19 +three +*/ diff --git a/streams/Looping.java b/streams/Looping.java new file mode 100644 index 00000000..29fe65f5 --- /dev/null +++ b/streams/Looping.java @@ -0,0 +1,17 @@ +// streams/Looping.java +import static onjava.Repeat.*; + +public class Looping { + static void hi() { System.out.println("Hi!"); } + public static void main(String[] args) { + repeat(3, () -> System.out.println("Looping!")); + repeat(2, Looping::hi); + } +} +/* Output: +Looping! +Looping! +Looping! +Hi! +Hi! +*/ diff --git a/streams/MICollision.java b/streams/MICollision.java new file mode 100644 index 00000000..b8204c13 --- /dev/null +++ b/streams/MICollision.java @@ -0,0 +1,47 @@ +// streams/MICollision.java +import java.util.*; + +interface Bob1 { + default void bob() { System.out.println("Bob1::bob"); } +} + +interface Bob2 { + default void bob() { System.out.println("Bob2::bob"); } +} + +// class Bob implements Bob1, Bob2 {} +/* Produces: +error: class Bob inherits unrelated defaults +for bob() from types Bob1 and Bob2 +class Bob implements Bob1, Bob2 {} +^ +1 error +*/ + +interface Sam1 { + default void sam() { System.out.println("Sam1::sam"); } +} + +interface Sam2 { + default void sam(int i) { System.out.println(i * 2); } +} + +// This works because the argument lists are distinct: +class Sam implements Sam1, Sam2 {} + +interface Max1 { + default void max() { System.out.println("Max1::max"); } +} + +interface Max2 { + default int max() { return 47; } +} + +// class Max implements Max1, Max2 {} +/* Produces: +error: types Max2 and Max1 are incompatible; +both define max(), but with unrelated return types +class Max implements Max1, Max2 {} +^ +1 error +*/ diff --git a/streams/Machine.java b/streams/Machine.java new file mode 100644 index 00000000..4e5b1e1b --- /dev/null +++ b/streams/Machine.java @@ -0,0 +1,31 @@ +// streams/Machine.java +import java.util.*; + +class Bing implements Operation { + public void execute() { + Operation.show("Bing"); + } +} + +public class Machine { + public static void main(String[] args) { + Operation.runOps(Arrays.asList( + new Bing(), + new Operation() { + public void execute() { + Operation.show("Anon"); + } + }, + () -> Operation.show("Crack"), + () -> Operation.show("Twist"), + () -> Operation.show("Pop") + )); + } +} +/* Output: +Bing +Anon +Crack +Twist +Pop +*/ diff --git a/streams/Machine2.java b/streams/Machine2.java new file mode 100644 index 00000000..4aa7d91a --- /dev/null +++ b/streams/Machine2.java @@ -0,0 +1,19 @@ +// streams/Machine2.java +import java.util.*; + +public class Machine2 { + public static void main(String[] args) { + Arrays.stream(new Operation[] { + () -> Operation.show("Bing"), + () -> Operation.show("Crack"), + () -> Operation.show("Twist"), + () -> Operation.show("Pop") + }).forEach(Operation::execute); + } +} +/* Output: +Bing +Crack +Twist +Pop +*/ diff --git a/streams/MapCollector.java b/streams/MapCollector.java new file mode 100644 index 00000000..a009780c --- /dev/null +++ b/streams/MapCollector.java @@ -0,0 +1,45 @@ +// streams/MapCollector.java +import java.util.*; +import java.util.stream.*; + +class Pair { + public final Character c; + public final Integer i; + public Pair(Character c, Integer i) { + this.c = c; + this.i = i; + } + public Character getC() { return c; } + public Integer getI() { return i; } + @Override + public String toString() { + return "Pair(" + c + ", " + i + ")"; + } +} + +class RandomPair { + Random rand = new Random(47); + // An infinite iterator of random capital letters: + Iterator capChars = rand.ints(48,122) + .filter(i -> i > 65 && i < 90) + .mapToObj(i -> (char)i) + .iterator(); + public Stream stream() { + return rand.ints(100, 1000).distinct() + .mapToObj(i -> new Pair(capChars.next(), i)); + } +} + +public class MapCollector { + public static void main(String[] args) { + Map map = + new RandomPair().stream() + .limit(8) + .collect( + Collectors.toMap(Pair::getI, Pair::getC)); + System.out.println(map); + } +} +/* Output: +{416=E, 322=O, 309=F, 293=G, 328=W, 858=S, 668=R, 622=L} +*/ diff --git a/streams/MultipleInheritance.java b/streams/MultipleInheritance.java new file mode 100644 index 00000000..40ee42d4 --- /dev/null +++ b/streams/MultipleInheritance.java @@ -0,0 +1,30 @@ +// streams/MultipleInheritance.java +import java.util.*; + +interface One { + default void first() { System.out.println("first"); } +} + +interface Two { + default void second() { System.out.println("second"); } +} + +interface Three { + default void third() { System.out.println("third"); } +} + +class MI implements One, Two, Three {} + +public class MultipleInheritance { + public static void main(String[] args) { + MI mi = new MI(); + mi.first(); + mi.second(); + mi.third(); + } +} +/* Output: +first +second +third +*/ diff --git a/streams/NumericStreamInfo.java b/streams/NumericStreamInfo.java new file mode 100644 index 00000000..73271a34 --- /dev/null +++ b/streams/NumericStreamInfo.java @@ -0,0 +1,21 @@ +// streams/NumericStreamInfo.java +import java.util.*; +import java.util.stream.*; +import static streams.RandInts.*; + +public class NumericStreamInfo { + public static void main(String[] args) { + System.out.println(rands().average().getAsDouble()); + System.out.println(rands().max().getAsInt()); + System.out.println(rands().min().getAsInt()); + System.out.println(rands().sum()); + System.out.println(rands().summaryStatistics()); + } +} +/* Output: +507.94 +998 +8 +50794 +IntSummaryStatistics{count=100, sum=50794, min=8, average=507.940000, max=998} +*/ diff --git a/streams/Operation.java b/streams/Operation.java new file mode 100644 index 00000000..5922661e --- /dev/null +++ b/streams/Operation.java @@ -0,0 +1,13 @@ +// streams/Operation.java +import java.util.*; + +@FunctionalInterface +public interface Operation { + void execute(); + static void runOps(List ops) { + ops.forEach(Operation::execute); + } + static void show(String msg) { + System.out.println(msg); + } +} diff --git a/streams/OptionalBasics.java b/streams/OptionalBasics.java new file mode 100644 index 00000000..520ef8a7 --- /dev/null +++ b/streams/OptionalBasics.java @@ -0,0 +1,20 @@ +// streams/OptionalBasics.java +import java.util.*; +import java.util.stream.*; + +class OptionalBasics { + static void test(Optional optString) { + if(optString.isPresent()) + System.out.println(optString.get()); + else + System.out.println("Nothing inside!"); + } + public static void main(String[] args) { + test(Stream.of("Epithets").findFirst()); + test(Stream.empty().findFirst()); + } +} +/* Output: +Epithets +Nothing inside! +*/ diff --git a/streams/OptionalFilter.java b/streams/OptionalFilter.java new file mode 100644 index 00000000..0ac52cae --- /dev/null +++ b/streams/OptionalFilter.java @@ -0,0 +1,67 @@ +// streams/OptionalFilter.java +import java.util.*; +import java.util.stream.*; +import java.util.function.*; + +class OptionalFilter { + static String[] elements = { + "Foo", "", "Bar", "Baz", "Bingo" + }; + static Stream testStream() { + return Arrays.stream(elements); + } + static void test(String descr, Predicate pred) { + System.out.println(" ---( " + descr + " )---"); + for(int i = 0; i <= elements.length; i++) { + System.out.println( + testStream() + .skip(i) + .findFirst() + .filter(pred)); + } + } + public static void main(String[] args) { + test("true", str -> true); + test("false", str -> false); + test("str != \"\"", str -> str != ""); + test("str.length() == 3", str -> str.length() == 3); + test("startsWith(\"B\")", str -> str.startsWith("B")); + } +} +/* Output: + ---( true )--- +Optional[Foo] +Optional[] +Optional[Bar] +Optional[Baz] +Optional[Bingo] +Optional.empty + ---( false )--- +Optional.empty +Optional.empty +Optional.empty +Optional.empty +Optional.empty +Optional.empty + ---( str != "" )--- +Optional[Foo] +Optional.empty +Optional[Bar] +Optional[Baz] +Optional[Bingo] +Optional.empty + ---( str.length() == 3 )--- +Optional[Foo] +Optional.empty +Optional[Bar] +Optional[Baz] +Optional.empty +Optional.empty + ---( startsWith("B") )--- +Optional.empty +Optional.empty +Optional[Bar] +Optional[Baz] +Optional[Bingo] +Optional.empty +*/ diff --git a/streams/OptionalFlatMap.java b/streams/OptionalFlatMap.java new file mode 100644 index 00000000..c07ae0c1 --- /dev/null +++ b/streams/OptionalFlatMap.java @@ -0,0 +1,65 @@ +// streams/OptionalFlatMap.java +import java.util.*; +import java.util.stream.*; +import java.util.function.*; + +class OptionalFlatMap { + static String[] elements = { "12", "", "23", "45" }; + static Stream testStream() { + return Arrays.stream(elements); + } + static void + test(String descr, Function> func) { + System.out.println(" ---( " + descr + " )---"); + for(int i = 0; i <= elements.length; i++) { + System.out.println( + testStream() + .skip(i) + .findFirst() + .flatMap(func)); + } + } + public static void main(String[] args) { + + test("Add brackets", s -> Optional.of("[" + s + "]")); + + test("Increment", s -> { + try { + return Optional.of(Integer.parseInt(s) + 1 + ""); + } catch(NumberFormatException e) { + return Optional.of(s); + } + }); + + test("Replace", s -> Optional.of(s.replace("2", "9"))); + + test("Take last digit", s -> Optional.of(s.length() > 0 ? + s.charAt(s.length() - 1) + "" : s)); + } +} +/* Output: + ---( Add brackets )--- +Optional[[12]] +Optional[[]] +Optional[[23]] +Optional[[45]] +Optional.empty + ---( Increment )--- +Optional[13] +Optional[] +Optional[24] +Optional[46] +Optional.empty + ---( Replace )--- +Optional[19] +Optional[] +Optional[93] +Optional[45] +Optional.empty + ---( Take last digit )--- +Optional[2] +Optional[] +Optional[3] +Optional[5] +Optional.empty +*/ diff --git a/streams/OptionalMap.java b/streams/OptionalMap.java new file mode 100644 index 00000000..25b18a6e --- /dev/null +++ b/streams/OptionalMap.java @@ -0,0 +1,70 @@ +// streams/OptionalMap.java +import java.util.*; +import java.util.stream.*; +import java.util.function.*; + +class OptionalMap { + static String[] elements = { "12", "", "23", "45" }; + static Stream testStream() { + return Arrays.stream(elements); + } + static void + test(String descr, Function func) { + System.out.println(" ---( " + descr + " )---"); + for(int i = 0; i <= elements.length; i++) { + System.out.println( + testStream() + .skip(i) + .findFirst() // Produces an Optional + .map(func)); + } + } + public static void main(String[] args) { + + // If Optional is not empty, map() first extracts + // the contents which it then passes to the function: + + test("Add brackets", s -> "[" + s + "]"); + + test("Increment", s -> { + try { + return Integer.parseInt(s) + 1 + ""; + } catch(NumberFormatException e) { + return s; + } + }); + + test("Replace", s -> s.replace("2", "9")); + + test("Take last digit", s -> s.length() > 0 ? + s.charAt(s.length() - 1) + "" : s); + } + // After the function is finished, map() wraps the + // result in an Optional before returning it: +} +/* Output: + ---( Add brackets )--- +Optional[[12]] +Optional[[]] +Optional[[23]] +Optional[[45]] +Optional.empty + ---( Increment )--- +Optional[13] +Optional[] +Optional[24] +Optional[46] +Optional.empty + ---( Replace )--- +Optional[19] +Optional[] +Optional[93] +Optional[45] +Optional.empty + ---( Take last digit )--- +Optional[2] +Optional[] +Optional[3] +Optional[5] +Optional.empty +*/ diff --git a/streams/Optionals.java b/streams/Optionals.java new file mode 100644 index 00000000..040428c5 --- /dev/null +++ b/streams/Optionals.java @@ -0,0 +1,60 @@ +// streams/Optionals.java +import java.util.*; +import java.util.stream.*; +import java.util.function.*; + +class Optionals { + static void basics(Optional optString) { + if(optString.isPresent()) + System.out.println(optString.get()); + else + System.out.println("Nothing inside!"); + } + static void if_present(Optional optString) { + optString.ifPresent(str -> System.out.println(str)); + } + static void or_else(Optional optString) { + System.out.println(optString.orElse("Nada")); + } + static void or_else_get(Optional optString) { + System.out.println( + optString.orElseGet(() -> "Generated")); + } + static void or_else_throw(Optional optString) { + try { + System.out.println(optString.orElseThrow( + () -> new Exception("Supplied"))); + } catch(Exception e) { + System.out.println("Caught " + e); + } + } + static void + test(String testName, Consumer> cos) { + System.out.println(" === " + testName + " === "); + cos.accept(Stream.of("Epithets").findFirst()); + cos.accept(Stream.empty().findFirst()); + } + public static void main(String[] args) { + test("basics", Optionals::basics); + test("ifPresent", Optionals::if_present); + test("orElse", Optionals::or_else); + test("orElseGet", Optionals::or_else_get); + test("orElseThrow", Optionals::or_else_throw); + } +} +/* Output: + === basics === +Epithets +Nothing inside! + === ifPresent === +Epithets + === orElse === +Epithets +Nada + === orElseGet === +Epithets +Generated + === orElseThrow === +Epithets +Caught java.lang.Exception: Supplied +*/ diff --git a/streams/OptionalsFromEmptyStreams.java b/streams/OptionalsFromEmptyStreams.java new file mode 100644 index 00000000..df95a550 --- /dev/null +++ b/streams/OptionalsFromEmptyStreams.java @@ -0,0 +1,28 @@ +// streams/OptionalsFromEmptyStreams.java +import java.util.*; +import java.util.stream.*; + +class OptionalsFromEmptyStreams { + public static void main(String[] args) { + System.out.println(Stream.empty() + .findFirst()); + System.out.println(Stream.empty() + .findAny()); + System.out.println(Stream.empty() + .max(String.CASE_INSENSITIVE_ORDER)); + System.out.println(Stream.empty() + .min(String.CASE_INSENSITIVE_ORDER)); + System.out.println(Stream.empty() + .reduce((s1, s2) -> s1 + s2)); + System.out.println(IntStream.empty() + .average()); + } +} +/* Output: +Optional.empty +Optional.empty +Optional.empty +Optional.empty +Optional.empty +OptionalDouble.empty +*/ diff --git a/streams/Peeking.java b/streams/Peeking.java new file mode 100644 index 00000000..2c807d0d --- /dev/null +++ b/streams/Peeking.java @@ -0,0 +1,18 @@ +// streams/Peeking.java + +class Peeking { + public static void main(String[] args) throws Exception { + FileToWords.stream("Cheese.dat") + .skip(21) + .limit(4) + .map(w -> w + " ") + .peek(System.out::print) + .map(String::toUpperCase) + .peek(System.out::print) + .map(String::toLowerCase) + .forEach(System.out::print); + } +} +/* Output: +Well WELL well it's IT'S it's so SO so clean CLEAN clean +*/ diff --git a/streams/Prime.java b/streams/Prime.java new file mode 100644 index 00000000..9694c81a --- /dev/null +++ b/streams/Prime.java @@ -0,0 +1,41 @@ +// streams/Prime.java +import java.util.stream.*; +import static java.util.stream.LongStream.*; + +public class Prime { + public static boolean isPrime(long n) { + return range(2, (long)Math.sqrt(n) + 1) + .noneMatch(i -> n % i == 0); + } + public LongStream numbers() { + return iterate(2, i -> i + 1).filter(Prime::isPrime); + } + public static void main(String[] args) { + new Prime().numbers() + .limit(100) + .forEach(System.out::println); + } +} +/* Output: (First and last 10 Lines) +2 +3 +5 +7 +11 +13 +17 +19 +23 +29 +________...________...________...________...________ +467 +479 +487 +491 +499 +503 +509 +521 +523 +541 +*/ diff --git a/streams/RandInts.java b/streams/RandInts.java new file mode 100644 index 00000000..f070e84a --- /dev/null +++ b/streams/RandInts.java @@ -0,0 +1,12 @@ +// streams/RandInts.java +package streams; +import java.util.*; +import java.util.stream.*; + +public class RandInts { + private static int[] rints = + new Random(47).ints(0, 1000).limit(100).toArray(); + public static IntStream rands() { + return Arrays.stream(rints); + } +} diff --git a/streams/RandomGenerators.java b/streams/RandomGenerators.java new file mode 100644 index 00000000..6c918960 --- /dev/null +++ b/streams/RandomGenerators.java @@ -0,0 +1,83 @@ +// streams/RandomGenerators.java +import java.util.*; +import java.util.stream.*; + +public class RandomGenerators { + public static void show(Stream stream) { + stream + .limit(4) + .forEach(System.out::println); + System.out.println("++++++++"); + } + public static void main(String[] args) { + Random rand = new Random(47); + show(rand.ints().boxed()); + show(rand.longs().boxed()); + show(rand.doubles().boxed()); + // Control the lower and upper bounds: + show(rand.ints(10, 20).boxed()); + show(rand.longs(50, 100).boxed()); + show(rand.doubles(20, 30).boxed()); + // Control the stream size: + show(rand.ints(2).boxed()); + show(rand.longs(2).boxed()); + show(rand.doubles(2).boxed()); + // Control the stream size and bounds: + show(rand.ints(3, 3, 9).boxed()); + show(rand.longs(3, 12, 22).boxed()); + show(rand.doubles(3, 11.5, 12.3).boxed()); + } +} +/* Output: +-1172028779 +1717241110 +-2014573909 +229403722 +++++++++ +2955289354441303771 +3476817843704654257 +-8917117694134521474 +4941259272818818752 +++++++++ +0.2613610344283964 +0.0508673570556899 +0.8037155449603999 +0.7620665811558285 +++++++++ +16 +10 +11 +12 +++++++++ +65 +99 +54 +58 +++++++++ +29.86777681078574 +24.83968447804611 +20.09247112332014 +24.046793846338723 +++++++++ +1169976606 +1947946283 +++++++++ +2970202997824602425 +-2325326920272830366 +++++++++ +0.7024254510631527 +0.6648552384607359 +++++++++ +6 +7 +7 +++++++++ +17 +12 +20 +++++++++ +12.27872414236691 +11.732085449736195 +12.196509449817267 +++++++++ +*/ diff --git a/streams/RandomWords.java b/streams/RandomWords.java new file mode 100644 index 00000000..f312c3fe --- /dev/null +++ b/streams/RandomWords.java @@ -0,0 +1,36 @@ +// streams/RandomWords.java +import java.util.*; +import java.util.stream.*; +import java.util.function.*; +import java.io.*; +import java.nio.file.*; + +public class RandomWords implements Supplier { + List words = new ArrayList<>(); + Random rand = new Random(47); + RandomWords(String fname) throws IOException { + List lines = + Files.readAllLines(Paths.get(fname)); + // Skip the first line: + for(String line : lines.subList(1, lines.size())) { + for(String word : line.split("[ .?,]+")) + words.add(word.toLowerCase()); + } + } + public String get() { + return words.get(rand.nextInt(words.size())); + } + @Override + public String toString() { + return words.stream().collect(Collectors.joining(" ")); + } + public static void main(String[] args) throws Exception { + System.out.println( + Stream.generate(new RandomWords("Cheese.dat")) + .limit(10) + .collect(Collectors.joining(" "))); + } +} +/* Output: +it shop sir the much cheese by conclusion district is +*/ diff --git a/streams/Randoms.java b/streams/Randoms.java new file mode 100644 index 00000000..df464d76 --- /dev/null +++ b/streams/Randoms.java @@ -0,0 +1,22 @@ +// streams/Randoms.java +import java.util.*; + +public class Randoms { + public static void main(String[] args) { + new Random(47) + .ints(5, 20) + .distinct() + .limit(7) + .sorted() + .forEach(System.out::println); + } +} +/* Output: +6 +10 +13 +16 +17 +18 +19 +*/ diff --git a/streams/Ranges.java b/streams/Ranges.java new file mode 100644 index 00000000..90fb46d9 --- /dev/null +++ b/streams/Ranges.java @@ -0,0 +1,26 @@ +// streams/Ranges.java +import static java.util.stream.IntStream.*; + +public class Ranges { + public static void main(String[] args) { + // The traditional way: + int result = 0; + for(int i = 10; i < 20; i++) + result += i; + System.out.println(result); + + // for-in with a range: + result = 0; + for(int i : range(10, 20).toArray()) + result += i; + System.out.println(result); + + // Use streams: + System.out.println(range(10, 20).sum()); + } +} +/* Output: +145 +145 +145 +*/ diff --git a/streams/SelectElement.java b/streams/SelectElement.java new file mode 100644 index 00000000..bff592be --- /dev/null +++ b/streams/SelectElement.java @@ -0,0 +1,15 @@ +// streams/SelectElement.java +import java.util.*; +import java.util.stream.*; +import static streams.RandInts.*; + +public class SelectElement { + public static void main(String[] args) { + System.out.println(rands().findFirst().getAsInt()); + System.out.println(rands().findAny().getAsInt()); + } +} +/* Output: +258 +258 +*/ diff --git a/streams/Signal.java b/streams/Signal.java new file mode 100644 index 00000000..f27dd65a --- /dev/null +++ b/streams/Signal.java @@ -0,0 +1,28 @@ +// streams/Signal.java +import java.util.*; +import java.util.stream.*; +import java.util.function.*; + +public class Signal { + private final String msg; + public Signal(String msg) { this.msg = msg; } + public String getMsg() { return msg; } + @Override + public String toString() { + return "Signal(" + msg + ")"; + } + static class Generator implements Supplier { + Random rand = new Random(47); + public Signal get() { + switch(rand.nextInt(4)) { + case 1: return new Signal("dot"); + case 2: return new Signal("dash"); + default: return null; + } + } + } + public static Stream> stream() { + return Stream.generate(new Generator()) + .map(signal -> Optional.ofNullable(signal)); + } +} diff --git a/streams/SortedComparator.java b/streams/SortedComparator.java new file mode 100644 index 00000000..86576e66 --- /dev/null +++ b/streams/SortedComparator.java @@ -0,0 +1,16 @@ +// streams/SortedComparator.java +import java.util.*; + +public class SortedComparator { + public static void main(String[] args) throws Exception { + FileToWords.stream("Cheese.dat") + .skip(10) + .limit(10) + .sorted(Comparator.reverseOrder()) + .map(w -> w + " ") + .forEach(System.out::print); + } +} +/* Output: +you what to the that sir leads in district And +*/ diff --git a/streams/StreamOf.java b/streams/StreamOf.java new file mode 100644 index 00000000..d8cbdbb0 --- /dev/null +++ b/streams/StreamOf.java @@ -0,0 +1,24 @@ +// streams/StreamOf.java +import java.util.stream.*; + +public class StreamOf { + public static void main(String[] args) { + Stream.of(new Bubble(1), new Bubble(2), new Bubble(3)) + .forEach(System.out::println); + Stream.of("It's ", "a ", "wonderful ", + "day ", "for ", "pie!") + .forEach(System.out::print); + System.out.println(); + Stream.of(3.14159, 2.718, 1.618) + .forEach(System.out::println); + } +} +/* Output: +Bubble(1) +Bubble(2) +Bubble(3) +It's a wonderful day for pie! +3.14159 +2.718 +1.618 +*/ diff --git a/streams/StreamOfOptionals.java b/streams/StreamOfOptionals.java new file mode 100644 index 00000000..f0e369ce --- /dev/null +++ b/streams/StreamOfOptionals.java @@ -0,0 +1,37 @@ +// streams/StreamOfOptionals.java +import java.util.*; +import java.util.stream.*; + +public class StreamOfOptionals { + public static void main(String[] args) { + Signal.stream() + .limit(10) + .forEach(System.out::println); + System.out.println(" ---"); + Signal.stream() + .limit(10) + .filter(Optional::isPresent) + .map(Optional::get) + .forEach(System.out::println); + } +} +/* Output: +Optional[Signal(dash)] +Optional[Signal(dot)] +Optional[Signal(dash)] +Optional.empty +Optional.empty +Optional[Signal(dash)] +Optional.empty +Optional[Signal(dot)] +Optional[Signal(dash)] +Optional[Signal(dash)] + --- +Signal(dash) +Signal(dot) +Signal(dash) +Signal(dash) +Signal(dot) +Signal(dash) +Signal(dash) +*/ diff --git a/streams/StreamOfRandoms.java b/streams/StreamOfRandoms.java new file mode 100644 index 00000000..9146da4e --- /dev/null +++ b/streams/StreamOfRandoms.java @@ -0,0 +1,16 @@ +// streams/StreamOfRandoms.java +import java.util.*; +import java.util.stream.*; + +public class StreamOfRandoms { + static Random rand = new Random(47); + public static void main(String[] args) { + Stream.of(1, 2, 3, 4, 5) + .flatMapToInt(i -> IntStream.concat( + rand.ints(0, 100).limit(i), IntStream.of(-1))) + .forEach(n -> System.out.format("%d ", n)); + } +} +/* Output: +58 -1 55 93 -1 61 61 29 -1 68 0 22 7 -1 88 28 51 89 9 -1 +*/ diff --git a/streams/StreamOfStreams.java b/streams/StreamOfStreams.java new file mode 100644 index 00000000..5c4298c8 --- /dev/null +++ b/streams/StreamOfStreams.java @@ -0,0 +1,16 @@ +// streams/StreamOfStreams.java +import java.util.stream.*; + +public class StreamOfStreams { + public static void main(String[] args) { + Stream.of(1, 2, 3) + .map(i -> Stream.of("Gonzo", "Kermit", "Beaker")) + .map(e-> e.getClass().getName()) + .forEach(System.out::println); + } +} +/* Output: +java.util.stream.ReferencePipeline$Head +java.util.stream.ReferencePipeline$Head +java.util.stream.ReferencePipeline$Head +*/ diff --git a/streams/build.xml b/streams/build.xml new file mode 100644 index 00000000..dfcc5241 --- /dev/null +++ b/streams/build.xml @@ -0,0 +1,56 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/strings/JGrep.java b/strings/JGrep.java index 28d64524..26f1c461 100644 --- a/strings/JGrep.java +++ b/strings/JGrep.java @@ -2,7 +2,7 @@ // A very simple version of the "grep" program. // {Args: JGrep.java 'void|int|String'} import java.util.regex.*; -import com.mindviewinc.util.*; +import onjava.*; public class JGrep { public static void main(String[] args) throws Exception { diff --git a/strings/TheReplacements.java b/strings/TheReplacements.java index c05eef24..309f5306 100644 --- a/strings/TheReplacements.java +++ b/strings/TheReplacements.java @@ -1,6 +1,6 @@ // strings/TheReplacements.java import java.util.regex.*; -import com.mindviewinc.util.*; +import onjava.*; /*! Here's a block of text to use as input to the regular expression matcher. Note that we diff --git a/swt/ColorBoxes.java b/swt/ColorBoxes.java index b0d39ccc..8cf9d91d 100644 --- a/swt/ColorBoxes.java +++ b/swt/ColorBoxes.java @@ -8,7 +8,7 @@ import org.eclipse.swt.graphics.*; import org.eclipse.swt.layout.*; import java.util.concurrent.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; class CBox extends Canvas implements Runnable { class CBoxPaintListener implements PaintListener { diff --git a/swt/Menus.java b/swt/Menus.java index 7edcea2a..316edd1d 100644 --- a/swt/Menus.java +++ b/swt/Menus.java @@ -4,7 +4,7 @@ import swt.util.*; import org.eclipse.swt.*; import org.eclipse.swt.widgets.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class Menus implements SWTApplication { private static Shell shell; diff --git a/typeinfo/NullRobot.java b/typeinfo/NullRobot.java index 97c875de..12e7f0b3 100644 --- a/typeinfo/NullRobot.java +++ b/typeinfo/NullRobot.java @@ -2,7 +2,7 @@ // Using a dynamic proxy to create a Null Object. import java.lang.reflect.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; class NullRobotProxyHandler implements InvocationHandler { private String nullName; diff --git a/typeinfo/Person.java b/typeinfo/Person.java index caac7655..17f25080 100644 --- a/typeinfo/Person.java +++ b/typeinfo/Person.java @@ -1,6 +1,6 @@ // typeinfo/Person.java // A class with a Null Object. -import com.mindviewinc.util.*; +import onjava.*; class Person { public final String first; diff --git a/typeinfo/PetCount3.java b/typeinfo/PetCount3.java index 3a1212a8..27ac9ce5 100644 --- a/typeinfo/PetCount3.java +++ b/typeinfo/PetCount3.java @@ -2,7 +2,7 @@ // Using isInstance() import typeinfo.pets.*; import java.util.*; -import com.mindviewinc.util.*; +import onjava.*; public class PetCount3 { static class PetCounter diff --git a/typeinfo/PetCount4.java b/typeinfo/PetCount4.java index a08691b8..8b3d829a 100644 --- a/typeinfo/PetCount4.java +++ b/typeinfo/PetCount4.java @@ -1,6 +1,6 @@ // typeinfo/PetCount4.java import typeinfo.pets.*; -import com.mindviewinc.util.*; +import onjava.*; public class PetCount4 { public static void main(String[] args) { diff --git a/typeinfo/Robot.java b/typeinfo/Robot.java index 5ff5df05..ae70d82a 100644 --- a/typeinfo/Robot.java +++ b/typeinfo/Robot.java @@ -1,5 +1,5 @@ // typeinfo/Robot.java -import com.mindviewinc.util.*; +import onjava.*; import java.util.*; public interface Robot { diff --git a/ui/BorderLayout1.java b/ui/BorderLayout1.java index 67a76782..82c81da6 100644 --- a/ui/BorderLayout1.java +++ b/ui/BorderLayout1.java @@ -2,7 +2,7 @@ // Demonstrates BorderLayout. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class BorderLayout1 extends JFrame { public BorderLayout1() { diff --git a/ui/Borders.java b/ui/Borders.java index 80f34ad7..849bd716 100644 --- a/ui/Borders.java +++ b/ui/Borders.java @@ -3,7 +3,7 @@ import javax.swing.*; import javax.swing.border.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Borders extends JFrame { static JPanel showBorder(Border b) { diff --git a/ui/Button1.java b/ui/Button1.java index a667d87a..08027c1d 100644 --- a/ui/Button1.java +++ b/ui/Button1.java @@ -2,7 +2,7 @@ // Putting buttons on a Swing application. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Button1 extends JFrame { private JButton diff --git a/ui/Button2.java b/ui/Button2.java index 63a2a5bb..890ba0be 100644 --- a/ui/Button2.java +++ b/ui/Button2.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Button2 extends JFrame { private JButton diff --git a/ui/Button2b.java b/ui/Button2b.java index 6ebdebc4..89797e01 100644 --- a/ui/Button2b.java +++ b/ui/Button2b.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Button2b extends JFrame { private JButton diff --git a/ui/ButtonGroups.java b/ui/ButtonGroups.java index 07f5ffac..c25fed5c 100644 --- a/ui/ButtonGroups.java +++ b/ui/ButtonGroups.java @@ -5,7 +5,7 @@ import javax.swing.*; import javax.swing.border.*; import java.awt.*; import java.lang.reflect.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class ButtonGroups extends JFrame { private static String[] ids = { diff --git a/ui/Buttons.java b/ui/Buttons.java index 31ca2e74..2a969836 100644 --- a/ui/Buttons.java +++ b/ui/Buttons.java @@ -4,7 +4,7 @@ import javax.swing.*; import javax.swing.border.*; import javax.swing.plaf.basic.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Buttons extends JFrame { private JButton jb = new JButton("JButton"); diff --git a/ui/CheckBoxes.java b/ui/CheckBoxes.java index 2dd942be..836712b6 100644 --- a/ui/CheckBoxes.java +++ b/ui/CheckBoxes.java @@ -2,7 +2,7 @@ // Using JCheckBoxes. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class CheckBoxes extends JFrame { private JTextArea t = new JTextArea(6, 15); diff --git a/ui/ColorBoxes.java b/ui/ColorBoxes.java index 2cda61c6..7e2bcb0c 100644 --- a/ui/ColorBoxes.java +++ b/ui/ColorBoxes.java @@ -4,7 +4,7 @@ import javax.swing.*; import java.awt.*; import java.util.concurrent.*; import java.util.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; class CBox extends JPanel implements Runnable { private int pause; diff --git a/ui/ComboBoxes.java b/ui/ComboBoxes.java index b1302aeb..1c999615 100644 --- a/ui/ComboBoxes.java +++ b/ui/ComboBoxes.java @@ -2,7 +2,7 @@ // Using drop-down lists. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class ComboBoxes extends JFrame { private String[] description = { diff --git a/ui/Dialogs.java b/ui/Dialogs.java index bbac467d..d392086a 100644 --- a/ui/Dialogs.java +++ b/ui/Dialogs.java @@ -2,7 +2,7 @@ // Creating and using Dialog Boxes. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; class MyDialog extends JDialog { public MyDialog(JFrame parent) { diff --git a/ui/Faces.java b/ui/Faces.java index b82841e5..f6913912 100644 --- a/ui/Faces.java +++ b/ui/Faces.java @@ -2,7 +2,7 @@ // Icon behavior in JButtons. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Faces extends JFrame { private static Icon[] faces; diff --git a/ui/FileChooserTest.java b/ui/FileChooserTest.java index e4b81ef5..722e7d72 100644 --- a/ui/FileChooserTest.java +++ b/ui/FileChooserTest.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class FileChooserTest extends JFrame { private JTextField diff --git a/ui/FlowLayout1.java b/ui/FlowLayout1.java index 257f3113..826566ec 100644 --- a/ui/FlowLayout1.java +++ b/ui/FlowLayout1.java @@ -2,7 +2,7 @@ // Demonstrates FlowLayout. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class FlowLayout1 extends JFrame { public FlowLayout1() { diff --git a/ui/GridLayout1.java b/ui/GridLayout1.java index 42a1885b..485d6c79 100644 --- a/ui/GridLayout1.java +++ b/ui/GridLayout1.java @@ -2,7 +2,7 @@ // Demonstrates GridLayout. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class GridLayout1 extends JFrame { public GridLayout1() { diff --git a/ui/HTMLButton.java b/ui/HTMLButton.java index 643a57fc..9b403ce0 100644 --- a/ui/HTMLButton.java +++ b/ui/HTMLButton.java @@ -2,7 +2,7 @@ // Putting HTML text on Swing components. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class HTMLButton extends JFrame { private JButton b = new JButton( diff --git a/ui/InterruptableLongRunningCallable.java b/ui/InterruptableLongRunningCallable.java index ab3c94b8..69426f46 100644 --- a/ui/InterruptableLongRunningCallable.java +++ b/ui/InterruptableLongRunningCallable.java @@ -3,8 +3,8 @@ import javax.swing.*; import java.awt.*; import java.util.concurrent.*; -import com.mindviewinc.util.*; -import static com.mindviewinc.util.SwingConsole.*; +import onjava.*; +import static onjava.SwingConsole.*; class CallableTask extends Task implements Callable { diff --git a/ui/InterruptableLongRunningTask.java b/ui/InterruptableLongRunningTask.java index a05495ba..61ee672a 100644 --- a/ui/InterruptableLongRunningTask.java +++ b/ui/InterruptableLongRunningTask.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.util.concurrent.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; class Task implements Runnable { private static int counter = 0; diff --git a/ui/List.java b/ui/List.java index cc0bdea0..f5be40a8 100644 --- a/ui/List.java +++ b/ui/List.java @@ -4,7 +4,7 @@ import javax.swing.border.*; import javax.swing.event.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class List extends JFrame { private String[] flavors = { diff --git a/ui/LongRunningTask.java b/ui/LongRunningTask.java index 0e39304a..617b0df3 100644 --- a/ui/LongRunningTask.java +++ b/ui/LongRunningTask.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.util.concurrent.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class LongRunningTask extends JFrame { private JButton diff --git a/ui/LookAndFeel.java b/ui/LookAndFeel.java index 361dcbb3..e2796c5e 100644 --- a/ui/LookAndFeel.java +++ b/ui/LookAndFeel.java @@ -4,7 +4,7 @@ import javax.swing.*; import java.awt.*; import java.util.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class LookAndFeel extends JFrame { private String[] choices = diff --git a/ui/Menus.java b/ui/Menus.java index 9219ac26..a72b5af5 100644 --- a/ui/Menus.java +++ b/ui/Menus.java @@ -4,7 +4,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Menus extends JFrame { private String[] flavors = { diff --git a/ui/MessageBoxes.java b/ui/MessageBoxes.java index 4822cba3..9cd54668 100644 --- a/ui/MessageBoxes.java +++ b/ui/MessageBoxes.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class MessageBoxes extends JFrame { private JButton[] b = { diff --git a/ui/MonitoredLongRunningCallable.java b/ui/MonitoredLongRunningCallable.java index 81fc71a7..f10701c3 100644 --- a/ui/MonitoredLongRunningCallable.java +++ b/ui/MonitoredLongRunningCallable.java @@ -3,8 +3,8 @@ import javax.swing.*; import java.awt.*; import java.util.concurrent.*; -import com.mindviewinc.util.*; -import static com.mindviewinc.util.SwingConsole.*; +import onjava.*; +import static onjava.SwingConsole.*; class MonitoredCallable implements Callable { private static int counter = 0; diff --git a/ui/Popup.java b/ui/Popup.java index 7fed6804..a2d314cf 100644 --- a/ui/Popup.java +++ b/ui/Popup.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Popup extends JFrame { private JPopupMenu popup = new JPopupMenu(); diff --git a/ui/Progress.java b/ui/Progress.java index dd5890e9..1f708ab6 100644 --- a/ui/Progress.java +++ b/ui/Progress.java @@ -3,7 +3,7 @@ import javax.swing.*; import javax.swing.border.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class Progress extends JFrame { private JProgressBar pb = new JProgressBar(); diff --git a/ui/RadioButtons.java b/ui/RadioButtons.java index 196d7406..e3b0c3b8 100644 --- a/ui/RadioButtons.java +++ b/ui/RadioButtons.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class RadioButtons extends JFrame { private JTextField t = new JTextField(15); diff --git a/ui/ShowAddListeners.java b/ui/ShowAddListeners.java index b6abbb59..0bfe5929 100644 --- a/ui/ShowAddListeners.java +++ b/ui/ShowAddListeners.java @@ -5,7 +5,7 @@ import java.awt.*; import java.awt.event.*; import java.lang.reflect.*; import java.util.regex.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class ShowAddListeners extends JFrame { private JTextField name = new JTextField(25); diff --git a/ui/SimpleMenus.java b/ui/SimpleMenus.java index 61d29cbb..7c3d47cb 100644 --- a/ui/SimpleMenus.java +++ b/ui/SimpleMenus.java @@ -2,7 +2,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class SimpleMenus extends JFrame { private JTextField t = new JTextField(15); diff --git a/ui/SineWave.java b/ui/SineWave.java index ab9316b3..4fa83487 100644 --- a/ui/SineWave.java +++ b/ui/SineWave.java @@ -3,7 +3,7 @@ import javax.swing.*; import javax.swing.event.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; class SineDraw extends JPanel { private static final int SCALEFACTOR = 200; diff --git a/ui/TabbedPane1.java b/ui/TabbedPane1.java index c586e710..c2e51b12 100644 --- a/ui/TabbedPane1.java +++ b/ui/TabbedPane1.java @@ -2,7 +2,7 @@ // Demonstrates the Tabbed Pane. import javax.swing.*; import java.awt.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class TabbedPane1 extends JFrame { private String[] flavors = { diff --git a/ui/TextArea.java b/ui/TextArea.java index 0efe7856..d246ca07 100644 --- a/ui/TextArea.java +++ b/ui/TextArea.java @@ -3,8 +3,8 @@ import javax.swing.*; import java.awt.*; import java.util.*; -import com.mindviewinc.util.*; -import static com.mindviewinc.util.SwingConsole.*; +import onjava.*; +import static onjava.SwingConsole.*; public class TextArea extends JFrame { private JButton diff --git a/ui/TextFields.java b/ui/TextFields.java index 891653a3..1db3fa08 100644 --- a/ui/TextFields.java +++ b/ui/TextFields.java @@ -5,7 +5,7 @@ import javax.swing.event.*; import javax.swing.text.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class TextFields extends JFrame { private JButton diff --git a/ui/TextPane.java b/ui/TextPane.java index f936f66a..d088040f 100644 --- a/ui/TextPane.java +++ b/ui/TextPane.java @@ -3,8 +3,8 @@ import javax.swing.*; import java.awt.*; import java.util.function.*; -import com.mindviewinc.util.*; -import static com.mindviewinc.util.SwingConsole.*; +import onjava.*; +import static onjava.SwingConsole.*; public class TextPane extends JFrame { private JButton b = new JButton("Add Text"); diff --git a/ui/TicTacToe.java b/ui/TicTacToe.java index b07d9ccc..3bff75b0 100644 --- a/ui/TicTacToe.java +++ b/ui/TicTacToe.java @@ -3,7 +3,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class TicTacToe extends JFrame { private JTextField diff --git a/ui/TrackEvent.java b/ui/TrackEvent.java index 2fdbb557..5fb09842 100644 --- a/ui/TrackEvent.java +++ b/ui/TrackEvent.java @@ -4,7 +4,7 @@ import javax.swing.*; import java.awt.*; import java.awt.event.*; import java.util.*; -import static com.mindviewinc.util.SwingConsole.*; +import static onjava.SwingConsole.*; public class TrackEvent extends JFrame { private HashMap h = diff --git a/xml/build.xml b/xml/build.xml deleted file mode 100644 index 89894a0f..00000000 --- a/xml/build.xml +++ /dev/null @@ -1,14 +0,0 @@ - - - - - - - - - - - - - -