《Effective Java 第三版》——第二章 创建和销毁对象
《Effective Java 第三版》——第三章 所有对象都通用的方法
《Effective Java 第三版》——第四章 类和接口
《Effective Java 第三版》——第六章 枚举和注解
《Effective Java 第三版》——第七章 Lambda 和 Stream
package effectivejava.chapter7.item45.anagrams; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.stream.Stream; import static java.util.stream.Collectors.groupingBy; // Tasteful use of streams enhances clarity and conciseness (Page 205) public class HybridAnagrams { public static void main(String[] args) throws IOException { Path dictionary = Paths.get(args[0]); int minGroupSize = Integer.parseInt(args[1]); System.out.println("Working Directory =" + System.getProperty("user.dir")); try (Stream<String> words = Files.lines(dictionary)) { System.out.println(); Collection<List<String>> collectionValues = words.collect(groupingBy(word -> alphabetize(word))).values(); System.out.println(collectionValues); System.out.println(); } try (Stream<String> words = Files.lines(dictionary)) { words.collect(groupingBy(word -> alphabetize(word))) .values().stream() .filter(group -> group.size() >= minGroupSize) .forEach(g -> System.out.println(g.size() + ": " + g)); } } private static String alphabetize(String s) { char[] a = s.toCharArray(); Arrays.sort(a); return new String(a); } }
/Library/Java/JavaVirtualMachines/jdk-13.0.2.jdk/Contents/Home/bin/java -Dfile.encoding=UTF-8 -classpath /Users/didi/git/effective-java-3e-source-code/bin effectivejava.chapter7.item45.anagrams.HybridAnagrams ./src/effectivejava/chapter7/item45/anagrams/dict.txt 2 Working Directory =/Users/didi/git/effective-java-3e-source-code [[, , ], [Family], [Education], [ General sources], [ Museums, Museums], [ Citations], [ Notes], [References], [Life, Life, Life, Life, Life], [Published author], [See also, See also, See also]] 3: [, , ] 2: [ Museums, Museums] 5: [Life, Life, Life, Life, Life] 3: [See also, See also, See also] Process finished with exit code 0
Life
Family
Education
Published author
References
Notes
Citations
General sources
See also
See also
See also
Life
Life
Life
Life
Museums
Museums
说白了就是得把中间结果通过某种形式存下来
。。。效率会降低。。。
package effectivejava.chapter7.item45; import java.math.BigInteger; import java.util.stream.Stream; import static java.math.BigInteger.*; // Generating the first twent Mersenne primes using streams (Page 208) public class MersennePrimes { static Stream<BigInteger> primes() { return Stream.iterate(TWO, BigInteger::nextProbablePrime); } // public static void main(String[] args) { // primes().map(p -> TWO.pow(p.intValueExact()).subtract(ONE)) // .filter(mersenne -> mersenne.isProbablePrime(50)) // .limit(20) // .forEach(mp -> System.out.println(mp.bitLength() + ": " + mp)); // } public static void main(String[] args) { //primes().forEach(System.out::println); primes().map(p -> TWO.pow(p.intValueExact()).subtract(ONE)) .filter(mersenne -> mersenne.isProbablePrime(50)) .limit(10) .forEach(mp -> System.out.println(mp.bitLength() + ": " + mp)); } }
package effectivejava.chapter7.item45; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; import static java.util.stream.Collectors.*; // Generating the Cartesian product of two lists using iteration and streams (Page 209) public class Card { public enum Suit { SPADE, HEART, DIAMOND, CLUB } public enum Rank { ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING } private final Suit suit; private final Rank rank; @Override public String toString() { return rank + " of " + suit + "S"; } public Card(Suit suit, Rank rank) { this.suit = suit; this.rank = rank; } private static final List<Card> NEW_DECK = newDeck(); // // Iterative Cartesian product computation // private static List<Card> newDeck() { // List<Card> result = new ArrayList<>(); // for (Suit suit : Suit.values()) // for (Rank rank : Rank.values()) // result.add(new Card(suit, rank)); // return result; // } // Stream-based Cartesian product computation private static List<Card> newDeck() { return Stream.of(Suit.values()) .flatMap(suit -> Stream.of(Rank.values()) .map(rank -> new Card(suit, rank))) .collect(toList()); } public static void main(String[] args) { System.out.println(NEW_DECK); } }
深水区...
|
|
package effectivejava.chapter7.item47; import java.util.stream.Stream; import java.util.stream.StreamSupport; // Adapters from stream to iterable and vice-versa (Page 216) public class Adapters { // Adapter from Stream<E> to Iterable<E> ( public static <E> Iterable<E> iterableOf(Stream<E> stream) { return stream::iterator; } // Adapter from Iterable<E> to Stream<E> public static <E> Stream<E> streamOf(Iterable<E> iterable) { return StreamSupport.stream(iterable.spliterator(), false); } }
package effectivejava.chapter7.item47; import java.util.*; public class PowerSet { // Returns the power set of an input set as custom collection (Page 218) public static final <E> Collection<Set<E>> of(Set<E> s) { List<E> src = new ArrayList<>(s); if (src.size() > 30) throw new IllegalArgumentException("Set too big " + s); return new AbstractList<Set<E>>() { @Override public int size() { return 1 << src.size(); // 2 to the power srcSize } @Override public boolean contains(Object o) { return o instanceof Set && src.containsAll((Set)o); } @Override public Set<E> get(int index) { Set<E> result = new HashSet<>(); for (int i = 0; index != 0; i++, index >>= 1) if ((index & 1) == 1) result.add(src.get(i)); return result; } }; } public static void main(String[] args) { Set s = new HashSet(Arrays.asList(args)); System.out.println(PowerSet.of(s)); } }
package effectivejava.chapter7.item47; import java.util.*; import java.util.stream.IntStream; import java.util.stream.Stream; // Two ways to generate a stream of all the sublists of a list (Pages 219-20) public class SubLists { // Returns a stream of all the sublists of its input list (Page 219) public static <E> Stream<List<E>> of(List<E> list) { return Stream.concat(Stream.of(Collections.emptyList()), prefixes(list).flatMap(SubLists::suffixes)); } private static <E> Stream<List<E>> prefixes(List<E> list) { return IntStream.rangeClosed(1, list.size()) .mapToObj(end -> list.subList(0, end)); } private static <E> Stream<List<E>> suffixes(List<E> list) { return IntStream.range(0, list.size()) .mapToObj(start -> list.subList(start, list.size())); } // // Returns a stream of all the sublists of its input list, excluding the empty list // // This version is derived from the obvious iterative code (Page 220) // public static <E> Stream<List<E>> of(List<E> list) { // return IntStream.range(0, list.size()) // .mapToObj(start -> // IntStream.rangeClosed(start + 1, list.size()) // .mapToObj(end -> list.subList(start, end))) // .flatMap(x -> x); // } public static void main(String[] args) { List<String> list = Arrays.asList(args); SubLists.of(list).forEach(System.out::println); System.out.println("---------"); prefixes(list).forEach(System.out::println); System.out.println("---------"); suffixes(list).forEach(System.out::println); } }
package effectivejava.chapter7.item48; import java.math.BigInteger; import java.util.stream.LongStream; public class ParallelPrimeCounting { // Prime-counting stream pipeline - parallel version (Page 225) static long pi(long n) { return LongStream.rangeClosed(2, n) .parallel() .mapToObj(BigInteger::valueOf) .filter(i -> i.isProbablePrime(50)) .count(); } public static void main(String[] args) { System.out.println(pi(10_000_000)); } }
package effectivejava.chapter7.item48; import java.math.BigInteger; import java.util.stream.Stream; import static java.math.BigInteger.*; // Parallel stream-based program to generate the first 20 Mersenne primes - HANGS!!! (Page 222) public class ParallelMersennePrimes { public static void main(String[] args) { primes().map(p -> TWO.pow(p.intValueExact()).subtract(ONE)) .parallel() .filter(mersenne -> mersenne.isProbablePrime(50)) .limit(20) .forEach(System.out::println); } static Stream<BigInteger> primes() { return Stream.iterate(TWO, BigInteger::nextProbablePrime); } }