예제 #1
1
  static void lambdaTest() {
    Runnable r = () -> System.out.print("hello lambda");
    r.run();
    List<String> list = Arrays.asList("t1", "t2", "t334", "t4", "t567");
    list.parallelStream().filter(s -> s.length() == 2).forEach(System.out::println);

    list = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "15", "17");
    Map<String, Integer> integers =
        list.stream()
            .map(Integer::new)
            .filter(e -> e % 2 != 0)
            .distinct()
            .collect(Collectors.toMap(Object::toString, e -> e));
    System.out.println(integers);
    Stream.generate(Math::random).limit(10).forEach(System.out::println);

    new Thread(() -> System.out.println("hello lambda")).start();
    new Thread(
            () -> {
              System.out.println("hello lambda");
            })
        .start();

    List<String> words = Lists.newArrayList("ren", "wang", "li", "zhao", "ma");
    words.sort((w1, w2) -> Integer.compare((w1.length()), w2.length()));

    List<Integer> ints = Ints.asList(1, 2, 3, 4, 5);
    ints.sort(Integer::compare);

    //        words.forEach(e -> System.out.print(e));
    words.forEach(System.out::println);

    //        words.stream().map(w -> w.length());
    words.stream().map(String::length);

    //        words.stream().map(w -> new StringBuilder(w));
    words.stream().map(StringBuilder::new);

    Converter<String, Integer> converter; // (f) -> Integer.valueOf(f);
    converter = Integer::valueOf;
    Integer converted = converter.convert("123");
    System.out.println(converted);

    String[] arrayStr = new String[] {"a", "ab", "abc", "abcd"};

    Arrays.sort(arrayStr, (first, second) -> Integer.compare(first.length(), second.length()));
  }
예제 #2
0
  public static void main(String[] args) throws IOException {
    Path path = Paths.get("../alice.txt");
    String contents = new String(Files.readAllBytes(path), StandardCharsets.UTF_8);

    Stream<String> words = Stream.of(contents.split("[\\P{L}]+"));
    show("words", words);
    Stream<String> song = Stream.of("gently", "down", "the", "stream");
    show("song", song);
    Stream<String> silence = Stream.empty();
    silence = Stream.<String>empty(); // Explicit type specification
    show("silence", silence);

    Stream<String> echos = Stream.generate(() -> "Echo");
    show("echos", echos);

    Stream<Double> randoms = Stream.generate(Math::random);
    show("randoms", randoms);

    Stream<BigInteger> integers = Stream.iterate(BigInteger.ONE, n -> n.add(BigInteger.ONE));
    show("integers", integers);

    Stream<String> wordsAnotherWay = Pattern.compile("[\\P{L}]+").splitAsStream(contents);
    show("wordsAnotherWay", wordsAnotherWay);

    try (Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8)) {
      show("lines", lines);
    }
  }
예제 #3
0
 @Test
 public void _02_무한_스트림_생성() {
   // 상수 무한 스트림
   Stream<String> echos = Stream.generate(() -> "Echo");
   // 난수 무한 스트림
   Stream<Double> randoms = Stream.generate(Math::random);
   // 무한 수열 스트림
   Stream.iterate(BigInteger.ZERO, n -> n.add(BigInteger.ONE));
 }
예제 #4
0
  public static void main(String[] args) {
    /** 例①: 打印数列的前10项 */
    Stream<Long> fibonacci = Stream.generate(new FibonacciSupplier());
    fibonacci.limit(10).forEach(System.out::println);

    /** 例②: 打印数列的20~30项 */
    Stream<Long> fibonacci2 = Stream.generate(new FibonacciSupplier());
    List<Long> list = fibonacci2.skip(20).limit(10).collect(Collectors.toList());
    list.forEach(System.out::println);
  }
예제 #5
0
  public static void main(String[] args) {
    Stream<Double> piStream = Stream.generate(new PiSupplier());
    piStream.skip(1000000).limit(10).forEach(System.out::println);

    System.out.println("-------------------------------------------");

    Stream<Double> piStream_1 = Stream.generate(new PiSupplier());
    piStream_1
        .map(new EulerTransform())
        .map(new EulerTransform())
        .map(new EulerTransform())
        .map(new EulerTransform())
        .map(new EulerTransform())
        .map(new EulerTransform())
        .skip(10)
        .limit(20)
        .forEach(System.out::println);
  }
예제 #6
0
  @Test
  public void _04_서브스트림_추출() {
    // limit
    Stream<Double> randoms = Stream.generate(Math::random).limit(100);

    assertThat(randoms.count(), is(100L));

    // skip
    Stream<String> words = Stream.of(contents.split("[\\P{L}]+")).skip(1);
    assertThat(words.findFirst().get(), is("was"));
  }
예제 #7
0
 private ExpressionBuilder(
     ExpressionBuilder<T> parent, int defaultLevel, BinaryOperator<T>... precedence) {
   this.operations = precedence;
   this.parent = parent;
   this.defaultLevel = defaultLevel;
   this.levelHistory = new Stack<>();
   this.currentLevel = 0;
   this.operationDeclared = true;
   this.elements =
       Stream.generate(LinkedList::new).limit(operations.length).toArray(LinkedList[]::new);
 }
예제 #8
0
 // Usage example
 public static void main(String[] args) {
   List<Edge>[] graph = Stream.generate(ArrayList::new).limit(3).toArray(List[]::new);
   addEdge(graph, 0, 1, 3, 1);
   addEdge(graph, 0, 2, 2, 1);
   addEdge(graph, 1, 2, 2, 1);
   int[] res = minCostFlow(graph, 0, 2, Integer.MAX_VALUE);
   int flow = res[0];
   int flowCost = res[1];
   System.out.println(4 == flow);
   System.out.println(6 == flowCost);
 }
예제 #9
0
  private EvolutionStart<G, C> evolutionStart(
      final Iterable<Genotype<G>> genotypes, final long generation) {
    final Stream<Phenotype<G, C>> stream =
        Stream.concat(
            StreamSupport.stream(genotypes.spliterator(), false)
                .map(gt -> Phenotype.of(gt, generation, _fitnessFunction, _fitnessScaler)),
            Stream.generate(() -> newPhenotype(generation)));

    final Population<G, C> population = stream.limit(getPopulationSize()).collect(toPopulation());

    return EvolutionStart.of(population, generation);
  }
예제 #10
0
  private EvolutionStart<G, C> evolutionStart(
      final Population<G, C> population, final long generation) {
    final Stream<Phenotype<G, C>> stream =
        Stream.concat(
            population
                .stream()
                .map(p -> p.newInstance(p.getGeneration(), _fitnessFunction, _fitnessScaler)),
            Stream.generate(() -> newPhenotype(generation)));

    final Population<G, C> pop = stream.limit(getPopulationSize()).collect(toPopulation());

    return EvolutionStart.of(pop, generation);
  }
예제 #11
0
  public static void main(String[] args) {
    // 스트림 생성
    Stream<String> song = Stream.of("gently", "down", "the", "stream");

    // 난수 100개
    Stream<Double> randoms = Stream.generate(Math::random).limit(100);

    //
    Stream<String> uniqueWords = Stream.of("merrily", "merrily", "merrily", "gentyl").distinct();

    Stream<Double> greatFirst =
        randoms.sorted(Comparator.comparing(Double::doubleValue).reversed());
    greatFirst.forEach(System.out::println);
  }
예제 #12
0
 /**
  * 文字を繰り返します。
  *
  * @param target 文字
  * @param count 繰り返し回数
  * @return 文字列
  */
 public static String repeat(char target, int count) {
   return Stream.generate(() -> target) // targetを延々と連ねるStream<Character>を生成する。
       .limit(count) // 個数をcountに制限する。
       .map(String::valueOf) // 文字列に変換してStream<String>を生成する。
       .collect(Collectors.joining()); // 全要素を文字列連結する。
 }
예제 #13
0
 public static String repeat(String s, int count) {
   return Stream.generate(() -> s).limit(count).collect(Collectors.joining());
 }
예제 #14
0
  public void testIndexAndRelocateConcurrently() throws ExecutionException, InterruptedException {
    int halfNodes = randomIntBetween(1, 3);
    Settings[] nodeSettings =
        Stream.concat(
                Stream.generate(() -> Settings.builder().put("node.attr.color", "blue").build())
                    .limit(halfNodes),
                Stream.generate(() -> Settings.builder().put("node.attr.color", "red").build())
                    .limit(halfNodes))
            .toArray(Settings[]::new);
    List<String> nodes = internalCluster().startNodes(nodeSettings);
    String[] blueNodes = nodes.subList(0, halfNodes).stream().toArray(String[]::new);
    String[] redNodes = nodes.subList(halfNodes, nodes.size()).stream().toArray(String[]::new);
    logger.info("blue nodes: {}", (Object) blueNodes);
    logger.info("red nodes: {}", (Object) redNodes);
    ensureStableCluster(halfNodes * 2);

    assertAcked(
        prepareCreate(
            "test",
            Settings.builder()
                .put("index.routing.allocation.exclude.color", "blue")
                .put(indexSettings())
                .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, randomInt(halfNodes - 1))));
    assertAllShardsOnNodes("test", redNodes);
    int numDocs = randomIntBetween(100, 150);
    ArrayList<String> ids = new ArrayList<>();
    logger.info(" --> indexing [{}] docs", numDocs);
    IndexRequestBuilder[] docs = new IndexRequestBuilder[numDocs];
    for (int i = 0; i < numDocs; i++) {
      String id = randomRealisticUnicodeOfLength(10) + String.valueOf(i);
      ids.add(id);
      docs[i] =
          client().prepareIndex("test", "type1", id).setSource("field1", English.intToEnglish(i));
    }
    indexRandom(true, docs);
    SearchResponse countResponse = client().prepareSearch("test").get();
    assertHitCount(countResponse, numDocs);

    logger.info(" --> moving index to new nodes");
    Settings build =
        Settings.builder()
            .put("index.routing.allocation.exclude.color", "red")
            .put("index.routing.allocation.include.color", "blue")
            .build();
    client()
        .admin()
        .indices()
        .prepareUpdateSettings("test")
        .setSettings(build)
        .execute()
        .actionGet();

    // index while relocating
    logger.info(" --> indexing [{}] more docs", numDocs);
    for (int i = 0; i < numDocs; i++) {
      String id = randomRealisticUnicodeOfLength(10) + String.valueOf(numDocs + i);
      ids.add(id);
      docs[i] =
          client()
              .prepareIndex("test", "type1", id)
              .setSource("field1", English.intToEnglish(numDocs + i));
    }
    indexRandom(true, docs);
    numDocs *= 2;

    logger.info(" --> waiting for relocation to complete");
    ensureGreen("test"); // move all shards to the new nodes (it waits on relocation)

    final int numIters = randomIntBetween(10, 20);
    for (int i = 0; i < numIters; i++) {
      logger.info(" --> checking iteration {}", i);
      SearchResponse afterRelocation = client().prepareSearch().setSize(ids.size()).get();
      assertNoFailures(afterRelocation);
      assertSearchHits(afterRelocation, ids.toArray(new String[ids.size()]));
    }
  }