Format/Streamify

This commit is contained in:
Bruce Eckel 2017-01-20 21:30:44 -08:00
parent 18ade9f18e
commit f3ef6ec758
52 changed files with 332 additions and 180 deletions

View File

@ -23,7 +23,9 @@ public class AtUnitExample1 {
@Test private boolean m3() { return true; }
// Shows output for failure:
@Test boolean failureTest() { return false; }
@Test boolean anotherDisappointment() { return false; }
@Test boolean anotherDisappointment() {
return false;
}
}
/* Output:
annotations.AtUnitExample1

View File

@ -15,11 +15,14 @@ public class AtUnitExample4 {
"middle, and then thin again at the far end.";
private String word;
private Random rand = new Random(); // Time-based seed
public AtUnitExample4(String word) { this.word = word; }
public AtUnitExample4(String word) {
this.word = word;
}
public String getWord() { return word; }
public String scrambleWord() {
List<Character> chars =
Arrays.asList(ConvertTo.boxed(word.toCharArray()));
Arrays.asList(
ConvertTo.boxed(word.toCharArray()));
Collections.shuffle(chars, rand);
StringBuilder result = new StringBuilder();
for(char ch : chars)
@ -41,7 +44,7 @@ public class AtUnitExample4 {
return getWord().equals("are");
}
@Test boolean scramble1() {
// Change to specific seed to get verifiable results:
// Use specific seed to get verifiable results:
rand = new Random(47);
System.out.println("'" + getWord() + "'");
String scrambled = scrambleWord();

View File

@ -11,7 +11,9 @@ import onjava.*;
public class AtUnitExample5 {
private String text;
public AtUnitExample5(String text) { this.text = text; }
public AtUnitExample5(String text) {
this.text = text;
}
@Override
public String toString() { return text; }
@TestProperty static PrintWriter output;

View File

@ -9,11 +9,14 @@ package annotations;
import onjava.atunit.*;
import onjava.*;
public class AtUnitExternalTest extends AtUnitExample1 {
public class
AtUnitExternalTest extends AtUnitExample1 {
@Test boolean tMethodOne() {
return methodOne().equals("This is methodOne");
}
@Test boolean tMethodTwo() { return methodTwo() == 2; }
@Test boolean tMethodTwo() {
return methodTwo() == 2;
}
}
/* Output:
annotations.AtUnitExternalTest

View File

@ -12,7 +12,8 @@ public class PasswordUtils {
}
@UseCase(id = 48)
public String encryptPassword(String passwd) {
return new StringBuilder(passwd).reverse().toString();
return new StringBuilder(passwd)
.reverse().toString();
}
@UseCase(id = 49, description =
"New passwords can't equal previously used ones")

View File

@ -9,7 +9,8 @@ package annotations;
import onjava.atunit.*;
import onjava.*;
public class StackLStringTest extends StackL<String> {
public class
StackLStringTest extends StackL<String> {
@Test void tPush() {
push("one");
assert top().equals("one");

View File

@ -9,7 +9,7 @@ import static onjava.ArrayShow.*;
public class ArrayOptions {
public static void main(String[] args) {
// Arrays of objects:
BerylliumSphere[] a; // Local uninitialized variable
BerylliumSphere[] a; // Uninitialized local
BerylliumSphere[] b = new BerylliumSphere[5];
// The references inside the array are

View File

@ -10,12 +10,15 @@ class BerylliumSphere {
private static long counter;
private final long id = counter++;
@Override
public String toString() { return "Sphere " + id; }
public String toString() {
return "Sphere " + id;
}
}
public class CollectionComparison {
public static void main(String[] args) {
BerylliumSphere[] spheres = new BerylliumSphere[10];
BerylliumSphere[] spheres =
new BerylliumSphere[10];
for(int i = 0; i < 5; i++)
spheres[i] = new BerylliumSphere();
show(spheres);

View File

@ -20,7 +20,8 @@ public class TestCount {
show(a1);
a1 = new Count.Boolean().array(SZ + 2);
show(a1);
boolean[] a1b = new Count.Pboolean().array(SZ + 3);
boolean[] a1b =
new Count.Pboolean().array(SZ + 3);
show(a1b);
System.out.println("Byte");
@ -63,8 +64,9 @@ public class TestCount {
int[] a5 = new int[SZ];
Arrays.setAll(a5, new Count.Integer()::get);
show(a5);
Integer[] a5b = Stream.generate(new Count.Integer())
.limit(SZ + 1).toArray(Integer[]::new);
Integer[] a5b =
Stream.generate(new Count.Integer())
.limit(SZ + 1).toArray(Integer[]::new);
show(a5b);
a5b = new Count.Integer().array(SZ + 2);
show(a5b);
@ -105,8 +107,9 @@ public class TestCount {
double[] a8 = new double[SZ];
Arrays.setAll(a8, new Count.Double()::get);
show(a8);
Double[] a8b = Stream.generate(new Count.Double())
.limit(SZ + 1).toArray(Double[]::new);
Double[] a8b =
Stream.generate(new Count.Double())
.limit(SZ + 1).toArray(Double[]::new);
show(a8b);
a8b = new Count.Double().array(SZ + 2);
show(a8b);

View File

@ -20,7 +20,8 @@ public class TestRand {
show(a1);
a1 = new Rand.Boolean().array(SZ + 2);
show(a1);
boolean[] a1b = new Rand.Pboolean().array(SZ + 3);
boolean[] a1b =
new Rand.Pboolean().array(SZ + 3);
show(a1b);
System.out.println("Byte");
@ -63,8 +64,9 @@ public class TestRand {
int[] a5 = new int[SZ];
Arrays.setAll(a5, new Rand.Integer()::get);
show(a5);
Integer[] a5b = Stream.generate(new Rand.Integer())
.limit(SZ + 1).toArray(Integer[]::new);
Integer[] a5b =
Stream.generate(new Rand.Integer())
.limit(SZ + 1).toArray(Integer[]::new);
show(a5b);
a5b = new Rand.Integer().array(SZ + 2);
show(a5b);
@ -105,8 +107,9 @@ public class TestRand {
double[] a8 = new double[SZ];
Arrays.setAll(a8, new Rand.Double()::get);
show(a8);
Double[] a8b = Stream.generate(new Rand.Double())
.limit(SZ + 1).toArray(Double[]::new);
Double[] a8b =
Stream.generate(new Rand.Double())
.limit(SZ + 1).toArray(Double[]::new);
show(a8b);
a8b = new Rand.Double().array(SZ + 2);
show(a8b);

View File

@ -52,13 +52,17 @@ public class CarWash {
}
EnumSet<Cycle> cycles =
EnumSet.of(Cycle.BASIC, Cycle.RINSE);
public void add(Cycle cycle) { cycles.add(cycle); }
public void add(Cycle cycle) {
cycles.add(cycle);
}
public void washCar() {
for(Cycle c : cycles)
c.action();
}
@Override
public String toString() { return cycles.toString(); }
public String toString() {
return cycles.toString();
}
public static void main(String[] args) {
CarWash wash = new CarWash();
System.out.println(wash);

View File

@ -10,7 +10,8 @@ public enum ConstantSpecificMethod {
@Override
String getInfo() {
return
DateFormat.getDateInstance().format(new Date());
DateFormat.getDateInstance()
.format(new Date());
}
},
CLASSPATH {

View File

@ -11,15 +11,18 @@ import static enums.AlarmPoints.*;
public class EnumSets {
public static void main(String[] args) {
EnumSet<AlarmPoints> points =
EnumSet.noneOf(AlarmPoints.class); // Empty set
EnumSet.noneOf(AlarmPoints.class); // Empty
points.add(BATHROOM);
System.out.println(points);
points.addAll(EnumSet.of(STAIR1, STAIR2, KITCHEN));
points.addAll(
EnumSet.of(STAIR1, STAIR2, KITCHEN));
System.out.println(points);
points = EnumSet.allOf(AlarmPoints.class);
points.removeAll(EnumSet.of(STAIR1, STAIR2, KITCHEN));
points.removeAll(
EnumSet.of(STAIR1, STAIR2, KITCHEN));
System.out.println(points);
points.removeAll(EnumSet.range(OFFICE1, OFFICE4));
points.removeAll(
EnumSet.range(OFFICE1, OFFICE4));
System.out.println(points);
points = EnumSet.complementOf(points);
System.out.println(points);

View File

@ -16,16 +16,18 @@ public enum Input {
STOP { // This must be the last instance.
@Override
public int amount() { // Disallow
throw new RuntimeException("SHUT_DOWN.amount()");
throw new
RuntimeException("SHUT_DOWN.amount()");
}
};
int value; // In cents
Input(int value) { this.value = value; }
Input() {}
int amount() { return value; }; // In cents
static SplittableRandom rand = new SplittableRandom(47);
static Random rand = new Random(47);
public static Input randomSelection() {
// Don't include STOP:
return values()[rand.nextInt(values().length - 1)];
return
values()[rand.nextInt(values().length - 1)];
}
}

View File

@ -7,15 +7,21 @@
enum LikeClasses {
WINKEN {
@Override
void behavior() { System.out.println("Behavior1"); }
void behavior() {
System.out.println("Behavior1");
}
},
BLINKEN {
@Override
void behavior() { System.out.println("Behavior2"); }
void behavior() {
System.out.println("Behavior2");
}
},
NOD {
@Override
void behavior() { System.out.println("Behavior3"); }
void behavior() {
System.out.println("Behavior3");
}
};
abstract void behavior();
}

View File

@ -7,9 +7,13 @@ public enum OverrideConstantSpecific {
NUT, BOLT,
WASHER {
@Override
void f() { System.out.println("Overridden method"); }
void f() {
System.out.println("Overridden method");
}
};
void f() { System.out.println("default behavior"); }
void f() {
System.out.println("default behavior");
}
public static void main(String[] args) {
for(OverrideConstantSpecific ocs : values()) {
System.out.print(ocs + ": ");

View File

@ -7,7 +7,7 @@ import java.util.*;
import onjava.*;
class Mail {
// The NO's lower the probability of random selection:
// The NO's reduce probability of random selection:
enum GeneralDelivery {YES,NO1,NO2,NO3,NO4,NO5}
enum Scannability {UNSCANNABLE,YES1,YES2,YES3,YES4}
enum Readability {ILLEGIBLE,YES1,YES2,YES3,YES4}
@ -35,10 +35,13 @@ class Mail {
Mail m = new Mail();
m.generalDelivery =
Enums.random(GeneralDelivery.class);
m.scannability = Enums.random(Scannability.class);
m.readability = Enums.random(Readability.class);
m.scannability =
Enums.random(Scannability.class);
m.readability =
Enums.random(Readability.class);
m.address = Enums.random(Address.class);
m.returnAddress = Enums.random(ReturnAddress.class);
m.returnAddress =
Enums.random(ReturnAddress.class);
return m;
}
public static
@ -49,9 +52,13 @@ class Mail {
public Iterator<Mail> iterator() {
return new Iterator<Mail>() {
@Override
public boolean hasNext() { return n-- > 0; }
public boolean hasNext() {
return n-- > 0;
}
@Override
public Mail next() { return randomMail(); }
public Mail next() {
return randomMail();
}
@Override
public void remove() { // Not implemented
throw new UnsupportedOperationException();

View File

@ -26,15 +26,18 @@ public class Reflection {
return methods;
}
public static void main(String[] args) {
Set<String> exploreMethods = analyze(Explore.class);
Set<String> exploreMethods =
analyze(Explore.class);
Set<String> enumMethods = analyze(Enum.class);
System.out.println("Explore.containsAll(Enum)? " +
System.out.println(
"Explore.containsAll(Enum)? " +
exploreMethods.containsAll(enumMethods));
System.out.print("Explore.removeAll(Enum): ");
exploreMethods.removeAll(enumMethods);
System.out.println(exploreMethods);
// Decompile the code for the enum:
OSExecute.command("javap -cp build/classes/main Explore");
OSExecute.command(
"javap -cp build/classes/main Explore");
}
}
/* Output:

View File

@ -62,7 +62,7 @@ class Rock implements Item {
public class RoShamBo1 {
static final int SIZE = 20;
private static SplittableRandom rand = new SplittableRandom(47);
private static Random rand = new Random(47);
public static Item newItem() {
switch(rand.nextInt(3)) {
default:

View File

@ -6,14 +6,19 @@
import onjava.*;
enum SecurityCategory {
STOCK(Security.Stock.class), BOND(Security.Bond.class);
STOCK(Security.Stock.class),
BOND(Security.Bond.class);
Security[] values;
SecurityCategory(Class<? extends Security> kind) {
values = kind.getEnumConstants();
}
interface Security {
enum Stock implements Security { SHORT, LONG, MARGIN }
enum Bond implements Security { MUNICIPAL, JUNK }
enum Stock implements Security {
SHORT, LONG, MARGIN
}
enum Bond implements Security {
MUNICIPAL, JUNK
}
}
public Security randomSelection() {
return Enums.random(values);

View File

@ -14,7 +14,8 @@ public enum SpaceShip {
return id.charAt(0) + lower;
}
public static void main(String[] args) {
Stream.of(values()).forEach(System.out::println);
Stream.of(values())
.forEach(System.out::println);
}
}
/* Output:

View File

@ -125,7 +125,9 @@ public class VendingMachine {
// For a basic sanity check:
class RandomInputSupplier implements Supplier<Input> {
@Override
public Input get() { return Input.randomSelection(); }
public Input get() {
return Input.randomSelection();
}
}
// Create Inputs from a file of ';'-separated strings:
@ -147,7 +149,8 @@ class FileInputSupplier implements Supplier<Input> {
public Input get() {
if(!input.hasNext())
return null;
return Enum.valueOf(Input.class, input.next().trim());
return Enum.valueOf(
Input.class, input.next().trim());
}
}
/* Output:

View File

@ -10,8 +10,10 @@ import java.util.function.*;
enum CartoonCharacter
implements Supplier<CartoonCharacter> {
SLAPPY, SPANKY, PUNCHY, SILLY, BOUNCY, NUTTY, BOB;
private SplittableRandom rand = new SplittableRandom(47);
SLAPPY, SPANKY, PUNCHY,
SILLY, BOUNCY, NUTTY, BOB;
private Random rand =
new Random(47);
@Override
public CartoonCharacter get() {
return values()[rand.nextInt(values().length)];

View File

@ -8,15 +8,13 @@ import java.nio.file.*;
public class ListOfLines {
public static void
main(String[] args) throws Exception {
List<String> lines = Files.readAllLines(
Paths.get("../streams/Cheese.dat"));
for(String line : lines) {
if(line.startsWith("//"))
continue;
System.out.println(
line.substring(0, line.length()/2));
}
Files.readAllLines(
Paths.get("../streams/Cheese.dat"))
.stream()
.filter(line -> !line.startsWith("//"))
.map(line ->
line.substring(0, line.length()/2))
.forEach(System.out::println);
}
}
/* Output:

View File

@ -10,19 +10,26 @@ class Customer {
private static long counter = 1;
private final long id = counter++;
@Override
public String toString() { return "Customer " + id; }
public String toString() {
return "Customer " + id;
}
}
class Teller {
private static long counter = 1;
private final long id = counter++;
@Override
public String toString() { return "Teller " + id; }
public String toString() {
return "Teller " + id;
}
}
class Bank {
private List<BankTeller> tellers = new ArrayList<>();
public void put(BankTeller bt) { tellers.add(bt); }
private List<BankTeller> tellers =
new ArrayList<>();
public void put(BankTeller bt) {
tellers.add(bt);
}
}
public class BankTeller {
@ -32,17 +39,20 @@ public class BankTeller {
public static void main(String[] args) {
// Demonstrate create():
RandomList<Teller> tellers =
Suppliers.create(RandomList::new, Teller::new, 4);
Suppliers.create(
RandomList::new, Teller::new, 4);
// Demonstrate fill():
List<Customer> customers = Suppliers.fill(
new ArrayList<>(), Customer::new, 12);
customers.forEach(c -> serve(tellers.select(), c));
customers.forEach(c ->
serve(tellers.select(), c));
// Demonstrate assisted latent typing:
Bank bank = Suppliers.fill(
new Bank(), Bank::put, BankTeller::new, 3);
// Can also use second version of fill():
List<Customer> customers2 = Suppliers.fill(
new ArrayList<>(), List::add, Customer::new, 12);
new ArrayList<>(),
List::add, Customer::new, 12);
}
}
/* Output:

View File

@ -7,7 +7,9 @@ class Subtype extends BasicHolder<Subtype> {}
public class CRGWithBasicHolder {
public static void main(String[] args) {
Subtype st1 = new Subtype(), st2 = new Subtype();
Subtype
st1 = new Subtype(),
st2 = new Subtype();
st1.set(st2);
Subtype st3 = st1.get();
st1.f();

View File

@ -6,5 +6,7 @@
public class ComparablePet
implements Comparable<ComparablePet> {
@Override
public int compareTo(ComparablePet arg) { return 0; }
public int compareTo(ComparablePet arg) {
return 0;
}
}

View File

@ -11,7 +11,7 @@ interface OrdinaryGetter {
}
interface DerivedGetter extends OrdinaryGetter {
// Return type of overridden method is allowed to vary:
// Overridden method return type can vary:
@Override
Derived get();
}

View File

@ -2,30 +2,46 @@
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.util.stream.*;
class FixedSizeStack<T> {
private int index = 0;
private final int size;
private Object[] storage;
private int index = 0;
public FixedSizeStack(int size) {
this.size = size;
storage = new Object[size];
}
public void push(T item) { storage[index++] = item; }
public void push(T item) {
if(index < size)
storage[index++] = item;
}
@SuppressWarnings("unchecked")
public T pop() { return (T)storage[--index]; }
public T pop() {
return index == 0 ? null : (T)storage[--index];
}
@SuppressWarnings("unchecked")
Stream<T> stream() {
return (Stream<T>)Arrays.stream(storage);
}
}
public class GenericCast {
public static final int SIZE = 10;
static String[] letters =
"ABCDEFGHIJKLMNOPQRS".split("");
public static void main(String[] args) {
FixedSizeStack<String> strings =
new FixedSizeStack<>(SIZE);
Stream.of("A B C D E F G H I J".split(" "))
.forEach(s -> strings.push(s));
for(int i = 0; i < SIZE; i++)
System.out.print(strings.pop() + " ");
new FixedSizeStack<>(letters.length);
Arrays.stream("ABCDEFGHIJKLMNOPQRS".split(""))
.forEach(strings::push);
System.out.println(strings.pop());
strings.stream()
.map(s -> s + " ")
.forEach(System.out::print);
}
}
/* Output:
J I H G F E D C B A
S
A B C D E F G H I J K L M N O P Q R S
*/

View File

@ -4,5 +4,7 @@
// Visit http://OnJava8.com for more book information.
public class HasF {
public void f() { System.out.println("HasF.f()"); }
public void f() {
System.out.println("HasF.f()");
}
}

View File

@ -9,23 +9,19 @@ import java.util.function.*;
// Fill an array using a generator:
interface FillArray {
static <T> T[] fill(T[] a, Supplier<T> gen) {
for(int i = 0; i < a.length; i++)
a[i] = gen.get();
Arrays.setAll(a, n -> gen.get());
return a;
}
static int[] fill(int[] a, IntSupplier gen) {
for(int i = 0; i < a.length; i++)
a[i] = gen.getAsInt();
Arrays.setAll(a, n -> gen.getAsInt());
return a;
}
static long[] fill(long[] a, LongSupplier gen) {
for(int i = 0; i < a.length; i++)
a[i] = gen.getAsLong();
Arrays.setAll(a, n -> gen.getAsLong());
return a;
}
static double[] fill(double[] a, DoubleSupplier gen) {
for(int i = 0; i < a.length; i++)
a[i] = gen.getAsDouble();
Arrays.setAll(a, n -> gen.getAsDouble());
return a;
}
}

View File

@ -5,11 +5,15 @@
class Hamster extends ComparablePet
implements Comparable<ComparablePet> {
public int compareTo(ComparablePet arg) { return 0; }
public int compareTo(ComparablePet arg) {
return 0;
}
}
// Or just:
class Gecko extends ComparablePet {
public int compareTo(ComparablePet arg) { return 0; }
public int compareTo(ComparablePet arg) {
return 0;
}
}

View File

@ -35,7 +35,7 @@ public class SimpleClient2 implements Runnable {
// Enable auto-flush:
socket.getOutputStream())), true)
) {
for (int i = 0; i < 25; i++) {
for(int i = 0; i < 25; i++) {
out.println("Client " + id + ": " + i);
String str = in.readLine();
System.out.println(str);

View File

@ -17,7 +17,9 @@ public interface Count {
b = !b;
return java.lang.Boolean.valueOf(b);
}
public java.lang.Boolean get(int n) { return get(); }
public java.lang.Boolean get(int n) {
return get();
}
public java.lang.Boolean[] array(int sz) {
java.lang.Boolean[] result =
new java.lang.Boolean[sz];
@ -41,9 +43,12 @@ public interface Count {
private byte b;
@Override
public java.lang.Byte get() { return b++; }
public java.lang.Byte get(int n) { return get(); }
public java.lang.Byte get(int n) {
return get();
}
public java.lang.Byte[] array(int sz) {
java.lang.Byte[] result = new java.lang.Byte[sz];
java.lang.Byte[] result =
new java.lang.Byte[sz];
Arrays.setAll(result, n -> get());
return result;
}
@ -92,9 +97,12 @@ public interface Count {
short s;
@Override
public java.lang.Short get() { return s++; }
public java.lang.Short get(int n) { return get(); }
public java.lang.Short get(int n) {
return get();
}
public java.lang.Short[] array(int sz) {
java.lang.Short[] result = new java.lang.Short[sz];
java.lang.Short[] result =
new java.lang.Short[sz];
Arrays.setAll(result, n -> get());
return result;
}
@ -112,7 +120,9 @@ public interface Count {
int i;
@Override
public java.lang.Integer get() { return i++; }
public java.lang.Integer get(int n) { return get(); }
public java.lang.Integer get(int n) {
return get();
}
public java.lang.Integer[] array(int sz) {
java.lang.Integer[] result =
new java.lang.Integer[sz];
@ -135,14 +145,18 @@ public interface Count {
private long l;
@Override
public java.lang.Long get() { return l++; }
public java.lang.Long get(int n) { return get(); }
public java.lang.Long get(int n) {
return get();
}
public java.lang.Long[] array(int sz) {
java.lang.Long[] result = new java.lang.Long[sz];
java.lang.Long[] result =
new java.lang.Long[sz];
Arrays.setAll(result, n -> get());
return result;
}
}
public static class Plong implements LongSupplier {
public static
class Plong implements LongSupplier {
private long l;
public long get() { return l++; }
public long get(int n) { return get(); }
@ -159,9 +173,12 @@ public interface Count {
public java.lang.Float get() {
return java.lang.Float.valueOf(i++);
}
public java.lang.Float get(int n) { return get(); }
public java.lang.Float get(int n) {
return get();
}
public java.lang.Float[] array(int sz) {
java.lang.Float[] result = new java.lang.Float[sz];
java.lang.Float[] result =
new java.lang.Float[sz];
Arrays.setAll(result, n -> get());
return result;
}
@ -181,7 +198,9 @@ public interface Count {
public java.lang.Double get() {
return java.lang.Double.valueOf(i++);
}
public java.lang.Double get(int n) { return get(); }
public java.lang.Double get(int n) {
return get();
}
public java.lang.Double[] array(int sz) {
java.lang.Double[] result =
new java.lang.Double[sz];

View File

@ -6,7 +6,7 @@ package onjava;
import java.util.*;
public class Enums {
private static SplittableRandom rand = new SplittableRandom(47);
private static Random rand = new Random(47);
public static
<T extends Enum<T>> T random(Class<T> ec) {
return random(ec.getEnumConstants());

View File

@ -39,9 +39,12 @@ public interface Rand {
public java.lang.Byte get() {
return (byte)r.nextInt(MOD);
}
public java.lang.Byte get(int n) { return get(); }
public java.lang.Byte get(int n) {
return get();
}
public java.lang.Byte[] array(int sz) {
java.lang.Byte[] result = new java.lang.Byte[sz];
java.lang.Byte[] result =
new java.lang.Byte[sz];
Arrays.setAll(result, n -> get());
return result;
}
@ -80,9 +83,12 @@ public interface Rand {
public java.lang.Short get() {
return (short)r.nextInt(MOD);
}
public java.lang.Short get(int n) { return get(); }
public java.lang.Short get(int n) {
return get();
}
public java.lang.Short[] array(int sz) {
java.lang.Short[] result = new java.lang.Short[sz];
java.lang.Short[] result =
new java.lang.Short[sz];
Arrays.setAll(result, n -> get());
return result;
}
@ -99,7 +105,9 @@ public interface Rand {
public java.lang.Integer get() {
return r.nextInt(MOD);
}
public java.lang.Integer get(int n) { return get(); }
public java.lang.Integer get(int n) {
return get();
}
public java.lang.Integer[] array(int sz) {
int[] primitive = new Pint().array(sz);
java.lang.Integer[] result =
@ -112,7 +120,9 @@ public interface Rand {
public static class Pint implements IntSupplier {
SplittableRandom r = new SplittableRandom(47);
@Override
public int getAsInt() { return r.nextInt(MOD); }
public int getAsInt() {
return r.nextInt(MOD);
}
public int get(int n) { return getAsInt(); }
public int[] array(int sz) {
return r.ints(sz, 0, MOD).toArray();
@ -125,16 +135,20 @@ public interface Rand {
public java.lang.Long get() {
return r.nextLong(MOD);
}
public java.lang.Long get(int n) { return get(); }
public java.lang.Long get(int n) {
return get();
}
public java.lang.Long[] array(int sz) {
long[] primitive = new Plong().array(sz);
java.lang.Long[] result = new java.lang.Long[sz];
java.lang.Long[] result =
new java.lang.Long[sz];
for(int i = 0; i < sz; i++)
result[i] = primitive[i];
return result;
}
}
public static class Plong implements LongSupplier {
public static
class Plong implements LongSupplier {
SplittableRandom r = new SplittableRandom(47);
@Override
public long getAsLong() {
@ -152,9 +166,12 @@ public interface Rand {
public java.lang.Float get() {
return (float)trim(r.nextDouble());
}
public java.lang.Float get(int n) { return get(); }
public java.lang.Float get(int n) {
return get();
}
public java.lang.Float[] array(int sz) {
java.lang.Float[] result = new java.lang.Float[sz];
java.lang.Float[] result =
new java.lang.Float[sz];
Arrays.setAll(result, n -> get());
return result;
}
@ -165,7 +182,8 @@ public interface Rand {
}
}
static double trim(double d) {
return ((double)Math.round(d * 1000.0)) / 100.0;
return
((double)Math.round(d * 1000.0)) / 100.0;
}
public static class Double
implements Supplier<java.lang.Double> {
@ -174,9 +192,12 @@ public interface Rand {
public java.lang.Double get() {
return trim(r.nextDouble());
}
public java.lang.Double get(int n) { return get(); }
public java.lang.Double get(int n) {
return get();
}
public java.lang.Double[] array(int sz) {
double[] primitive = new Rand.Pdouble().array(sz);
double[] primitive =
new Rand.Pdouble().array(sz);
java.lang.Double[] result =
new java.lang.Double[sz];
for(int i = 0; i < sz; i++)
@ -184,13 +205,16 @@ public interface Rand {
return result;
}
}
public static class Pdouble implements DoubleSupplier {
public static
class Pdouble implements DoubleSupplier {
SplittableRandom r = new SplittableRandom(47);
@Override
public double getAsDouble() {
return trim(r.nextDouble());
}
public double get(int n) { return getAsDouble(); }
public double get(int n) {
return getAsDouble();
}
public double[] array(int sz) {
double[] result = r.doubles(sz).toArray();
Arrays.setAll(result,
@ -201,7 +225,7 @@ public interface Rand {
public static class String
implements Supplier<java.lang.String> {
SplittableRandom r = new SplittableRandom(47);
private int strlen = 7; // Default string length
private int strlen = 7; // Default length
public String() {}
public String(int strLength) {
strlen = strLength;
@ -213,7 +237,9 @@ public interface Rand {
StringBuilder::appendCodePoint,
StringBuilder::append).toString();
}
public java.lang.String get(int n) { return get(); }
public java.lang.String get(int n) {
return get();
}
public java.lang.String[] array(int sz) {
java.lang.String[] result =
new java.lang.String[sz];

View File

@ -5,6 +5,7 @@
// Counts instances of a type family
package onjava;
import java.util.*;
import java.util.stream.*;
public class
TypeCounter extends HashMap<Class<?>, Integer> {
@ -30,15 +31,11 @@ TypeCounter extends HashMap<Class<?>, Integer> {
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("{");
for(Map.Entry<Class<?>, Integer> pair : entrySet()) {
result.append(pair.getKey().getSimpleName());
result.append("=");
result.append(pair.getValue());
result.append(", ");
}
result.delete(result.length() - 2, result.length());
result.append("}");
return result.toString();
String result = entrySet().stream()
.map(pair -> String.format("%s=%s",
pair.getKey().getSimpleName(),
pair.getValue()))
.collect(Collectors.joining(", "));
return "{" + result + "}";
}
}

View File

@ -12,6 +12,7 @@ public class Aluminum extends patterns.trash.Aluminum
public Aluminum(double wt) { super(wt); }
@Override
public boolean addToBin(List<TypedBin> tbins) {
return tbins.stream().anyMatch(tb -> tb.add(this));
return tbins.stream()
.anyMatch(tb -> tb.add(this));
}
}

View File

@ -12,6 +12,7 @@ public class Cardboard extends patterns.trash.Cardboard
public Cardboard(double wt) { super(wt); }
@Override
public boolean addToBin(List<TypedBin> tbins) {
return tbins.stream().anyMatch(tb -> tb.add(this));
return tbins.stream()
.anyMatch(tb -> tb.add(this));
}
}

View File

@ -65,7 +65,8 @@ public class DoubleDispatch {
// individually-typed bins:
bins.sortIntoBins(bin);
// Perform sumValue for each bin...
bins.binSet().forEach(tb -> Trash.sumValue(tb.v));
bins.binSet()
.forEach(tb -> Trash.sumValue(tb.v));
// ... and for the master bin
Trash.sumValue(bin);
}

View File

@ -12,6 +12,7 @@ public class Glass extends patterns.trash.Glass
public Glass(double wt) { super(wt); }
@Override
public boolean addToBin(List<TypedBin> tbins) {
return tbins.stream().anyMatch(tb -> tb.add(this));
return tbins.stream()
.anyMatch(tb -> tb.add(this));
}
}

View File

@ -12,6 +12,7 @@ public class Paper extends patterns.trash.Paper
public Paper(double wt) { super(wt); }
@Override
public boolean addToBin(List<TypedBin> tbins) {
return tbins.stream().anyMatch(tb -> tb.add(this));
return tbins.stream()
.anyMatch(tb -> tb.add(this));
}
}

View File

@ -7,7 +7,7 @@ package patterns.doubledispatch;
import patterns.trash.*;
import java.util.*;
public abstract class TypedBin {
public class TypedBin {
List<Trash> v = new ArrayList<>();
protected boolean addIt(Trash t) {
v.add(t);

View File

@ -26,14 +26,14 @@ class Tbin<T extends Trash> extends ArrayList<T> {
}
class TbinList<T extends Trash>
extends ArrayList<Tbin<? extends T>> { // [*1*]
extends ArrayList<Tbin<? extends T>> { // [1]
boolean sort(T t) {
for(Tbin<? extends T> ts : this)
if(ts.grab(t))
return true;
return false; // bin not found for t
}
void sortBin(Tbin<T> bin) { // [*2*]
void sortBin(Tbin<T> bin) { // [2]
for(T aBin : bin)
if(!sort(aBin))
System.err.println("Bin not found");
@ -53,7 +53,7 @@ public class RecycleC {
// add one line here: [*3*]
trashBins.add(new Tbin<>(Cardboard.class));
trashBins.sortBin(bin); // [*4*]
trashBins.sortBin(bin); // [4]
trashBins.forEach(Trash::sumValue);
Trash.sumValue(bin);

View File

@ -13,9 +13,9 @@ public class SpecialCollector {
.collect(ArrayList::new,
ArrayList::add,
ArrayList::addAll);
for(String s : words)
if(s.equals("cheese"))
System.out.println(s);
words.stream()
.filter(s -> s.equals("cheese"))
.forEach(System.out::println);
}
}
/* Output:

View File

@ -7,7 +7,8 @@ import java.util.regex.*;
public class Finding {
public static void main(String[] args) {
Matcher m = Pattern.compile("\\w+")
.matcher("Evening is full of the linnet's wings");
.matcher(
"Evening is full of the linnet's wings");
while(m.find())
System.out.print(m.group() + " ");
System.out.println();

View File

@ -1,4 +1,4 @@
// onjava/Hex.java
// strings/Hex.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

View File

@ -3,11 +3,11 @@
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.
import java.util.*;
import java.util.stream.*;
public class UsingStringBuilder {
public static Random rand = new Random(47);
@Override
public String toString() {
public static String string1() {
Random rand = new Random(47);
StringBuilder result = new StringBuilder("[");
for(int i = 0; i < 25; i++) {
result.append(rand.nextInt(100));
@ -17,12 +17,21 @@ public class UsingStringBuilder {
result.append("]");
return result.toString();
}
public static String string2() {
String result = new Random(47)
.ints(25, 0, 100)
.mapToObj(Integer::toString)
.collect(Collectors.joining(", "));
return "[" + result + "]";
}
public static void main(String[] args) {
UsingStringBuilder usb = new UsingStringBuilder();
System.out.println(usb);
System.out.println(string1());
System.out.println(string2());
}
}
/* Output:
[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9,
78, 98, 61, 20, 58, 16, 40, 11, 22, 4]
[58, 55, 93, 61, 61, 29, 68, 0, 22, 7, 88, 28, 51, 89, 9,
78, 98, 61, 20, 58, 16, 40, 11, 22, 4]
*/

View File

@ -22,7 +22,8 @@ public class ModifyingPrivateFields {
System.out.println(pf);
Field f = pf.getClass().getDeclaredField("i");
f.setAccessible(true);
System.out.println("f.getInt(pf): " + f.getInt(pf));
System.out.println(
"f.getInt(pf): " + f.getInt(pf));
f.setInt(pf, 47);
System.out.println(pf);
f = pf.getClass().getDeclaredField("s");

View File

@ -9,8 +9,8 @@ import onjava.*;
import typeinfo.pets.*;
public class PetCount3 {
static class Counter
extends LinkedHashMap<Class<? extends Pet>, Integer> {
static class Counter extends
LinkedHashMap<Class<? extends Pet>, Integer> {
public Counter() {
super(LiteralPetCreator.ALL_TYPES.stream()
.map(lpc -> Pair.make(lpc, 0))
@ -19,24 +19,19 @@ public class PetCount3 {
}
public void count(Pet pet) {
// Class.isInstance() eliminates instanceofs:
for(Map.Entry<Class<? extends Pet>, Integer>
pair : entrySet())
if(pair.getKey().isInstance(pet))
put(pair.getKey(), pair.getValue() + 1);
entrySet().stream()
.filter(pair -> pair.getKey().isInstance(pet))
.forEach(pair ->
put(pair.getKey(), pair.getValue() + 1));
}
@Override
public String toString() {
StringBuilder result = new StringBuilder("{");
for(Map.Entry<Class<? extends Pet>, Integer>
pair : entrySet()) {
result.append(pair.getKey().getSimpleName());
result.append("=");
result.append(pair.getValue());
result.append(", ");
}
result.delete(result.length() - 2, result.length());
result.append("}");
return result.toString();
String result = entrySet().stream()
.map(pair -> String.format("%s=%s",
pair.getKey().getSimpleName(),
pair.getValue()))
.collect(Collectors.joining(", "));
return "{" + result + "}";
}
}
public static void main(String[] args) {

View File

@ -25,12 +25,13 @@ class Position {
public Person getPerson() { return person; }
public void setPerson(Person newPerson) {
// Uses empty Person if newPerson is null:
person =
Optional.ofNullable(newPerson).orElse(new Person());
person = Optional.ofNullable(newPerson)
.orElse(new Person());
}
@Override
public String toString() {
return "Position: " + title + ", Employee: " + person;
return "Position: " + title +
", Employee: " + person;
}
public static void main(String[] args) {
System.out.println(new Position("CEO"));

View File

@ -30,15 +30,21 @@ interface SomeMethods {
class Implementation implements SomeMethods {
@Override
public void boring1() { System.out.println("boring1"); }
public void boring1() {
System.out.println("boring1");
}
@Override
public void boring2() { System.out.println("boring2"); }
public void boring2() {
System.out.println("boring2");
}
@Override
public void interesting(String arg) {
System.out.println("interesting " + arg);
}
@Override
public void boring3() { System.out.println("boring3"); }
public void boring3() {
System.out.println("boring3");
}
}
class SelectingMethods {