public void example() {
    System.out.println(
        Stream.of(IntStream.of(1), IntStream.of(2)).flatMapToInt((IntStream s) -> s).sum());

    // unchanged, it's not using the varargs overload
    System.out.println(Stream.of(IntStream.of(1)).flatMap(s -> s.boxed()).mapToInt(i -> i).sum());
  }
  public static void main(String... args) {

    /*
    -------------------------------------------------------------------------
    From obj to ...
    -------------------------------------------------------------------------
    */
    Stream<String> streamOfStrings = Stream.of("un", "deux", "trois");
    Function<String, StringBuilder> function = StringBuilder::new;
    streamOfStrings.map(function) /*.forEach(System.out::println)*/;
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToIntFunction<String> toIntFunction = String::length;
    IntStream streamOfInts = streamOfStrings.mapToInt(toIntFunction);
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToDoubleFunction<String> toDoubleFunction = String::length;
    DoubleStream streamOfDoubles = streamOfStrings.mapToDouble(toDoubleFunction);
    streamOfStrings = Stream.of("un", "deux", "trois");
    ToLongFunction<String> toLongFunction = String::length;
    LongStream streamOfLongs = streamOfStrings.mapToLong(toLongFunction);

    /*
    -------------------------------------------------------------------------
    From int to ...
    -------------------------------------------------------------------------
    */
    IntUnaryOperator plusplus = i -> i++;
    IntStream.of(1, 2, 3).map(plusplus)
    /*.forEach(x->System.out.println(x))*/ ;
    IntFunction<String> intFunction = i -> "" + i;
    IntStream.of(1, 2, 3).mapToObj(intFunction)
    /*.forEach(System.out::println)*/ ;
    IntToDoubleFunction itdf = i -> i;
    IntStream.of(1, 2, 3).mapToDouble(itdf)
    /*.forEach(System.out::println)*/ ;
    IntToLongFunction itlf = i -> i;
    IntStream.of(1, 2, 3).mapToLong(itlf)
    /*.forEach(System.out::println)*/ ;

    /*
    -------------------------------------------------------------------------
    From long to ...
    -------------------------------------------------------------------------
    */
    LongUnaryOperator times = l -> l * l;
    LongStream.of(1L, 2L, 3L).map(times)
    /*.forEach(System.out::println)*/ ;
    LongFunction<String> lf = l -> "toto";
    LongStream.of(1L, 2L, 3L).mapToObj(lf);

    /*
    -------------------------------------------------------------------------
    From double to ...
    -------------------------------------------------------------------------
    */
    DoubleToIntFunction dtif = d -> (int) d;
    DoubleStream.of(1.3, 1.5, 1.6).mapToInt(dtif).forEach(System.out::println);
  }
Beispiel #3
0
  @Test
  public void reduce() {
    IntStream stream = IntStream.of(1, 2, 3, 4);

    assertEquals(10, stream.reduce(0, (a, b) -> a + b));

    Stream<Integer> stream2 = Arrays.asList(1, 2, 3, 4).stream();

    stream2.reduce(0, (a, b) -> a + b);

    // obviously the operations can be more complex :)

    Stream<Integer> stream3 = Arrays.asList(1, 2, 3, 4).stream();

    // reduce is a superset of map :D
    System.err.println(
        stream3.reduce(
            new ArrayList<Integer>(),
            (List<Integer> a, Integer b) -> {
              a.add(b);
              return a;
            },
            (a, b) -> {
              List<Integer> c = new ArrayList<>(a);
              c.addAll(b);
              return c;
            }));
  }
  /**
   * Calculates the column totals.
   *
   * @return never {@code null}.
   */
  private long[] calculateColumnTotals() {
    final long[] result = new long[counts.length];

    for (int i = 0; i < counts.length; i++) {
      result[i] = IntStream.of(counts[i]).sum();
    }
    return result;
  }
 @Test
 void capacityTest() {
   for (final int size : new int[] {1000, 2000, 5000, 7000, 12000}) {
     final int capacity = new HopscotchCollection<>(size).capacity();
     Assert.assertTrue(capacity >= size);
     Assert.assertTrue(capacity < 2 * size);
     final List<Integer> legalSizes =
         IntStream.of(HopscotchCollection.legalSizes).boxed().collect(Collectors.toList());
     Assert.assertTrue(legalSizes.contains(capacity));
   }
 }
Beispiel #6
0
 private static String generateNewsPaperText(
     List<Knowledge> knowledgeList, int[] knowledgeIndices, World world) {
   StringBuilder builder = new StringBuilder();
   KnowledgeToDescriptionMapper mapper = new KnowledgeToDescriptionMapper();
   List<Integer> knowledgeInts =
       IntStream.of(knowledgeIndices).boxed().collect(Collectors.toList());
   for (int i = 0; i < knowledgeList.size(); i++) {
     Knowledge knowledge = knowledgeList.get(i);
     if (knowledgeInts.contains(knowledge.getId())) {
       builder.append(mapper.getStatementDescription(knowledge, world)).append(". ");
     }
   }
   return builder.toString();
 }
Beispiel #7
0
 public Collection<Integer> getRtcWorkItemRange() {
   String rangesString = props.getProperty(RTC_WORKITEM_ID_RANGE);
   String[] ranges = rangesString.split(",");
   IntStream intStream = IntStream.of();
   for (String range : ranges) {
     String[] splitted = range.split("\\.\\.");
     int from = Integer.parseInt(splitted[0].trim());
     if (splitted.length == 1) {
       intStream = IntStream.concat(intStream, IntStream.rangeClosed(from, from));
     } else {
       int to = Integer.parseInt(splitted[1].trim());
       intStream = IntStream.concat(intStream, IntStream.rangeClosed(from, to));
     }
   }
   return intStream.boxed().collect(Collectors.toList());
 }
  private <E extends RuntimeException> void assertIntToDoubleFunction(
      IntToDoubleFunction test, Class<E> type) {
    assertNotNull(test);
    try {
      test.applyAsDouble(0);
      fail();
    } catch (RuntimeException e) {
      assertException(type, e, "0");
    }

    try {
      IntStream.of(1, 2, 3).mapToDouble(test);
    } catch (RuntimeException e) {
      assertException(type, e, "1");
    }
  }
  /** Writes the column summary output table. */
  private void writeColumnSummaryOutput() {
    if (columnSummaryOutputWriter == null) {
      return;
    }

    final long totalSize = targetCollection.totalSize();

    final List<String> columnNames = countColumns.columnNames();
    for (int i = 0; i < columnNames.size(); i++) {
      final long sum = IntStream.of(counts[i]).sum();
      columnSummaryOutputWriter.println(
          String.join(
              COLUMN_SEPARATOR,
              columnNames.get(i),
              String.valueOf(sum),
              String.format(AVERAGE_DOUBLE_FORMAT, sum / (double) totalSize)));
    }
  }
Beispiel #10
0
  public static void main(String[] args) throws Exception {
    Algorithm algorithm = null;

    for (int funcNumber = 1; funcNumber <= 28; funcNumber++) {
      System.out.println("Test function;" + funcNumber);
      //            System.out.println("--------------------------------------------------");

      double[] fitnesses = new double[reps];
      //            for (int i = 0; i < reps; i++) {
      //                algorithm = new Pso(swarmSize, iterations, dim, c1, c2, maxVelocity, new
      // Cec2013(funcNumber));
      //                fitnesses[i] = algorithm.run().fitness;
      //            }
      //            printAlgorithmName(algorithm);
      //            printStats(fitnesses);
      //
      //            fitnesses = new double[reps];

      int[] roundsInIterations = new int[reps];
      int[] repulsiveCycles = new int[reps];
      double[][] gbestValues = new double[reps][1000];
      for (int i = 0; i < reps; i++) {
        algorithm =
            new NetPso(
                swarmSize,
                iterations,
                dim,
                c1,
                c2,
                maxVelocity,
                new Cec2013(funcNumber),
                degreeLimit,
                repulsiveRoundsLimit,
                maxRepulsionIteration);
        fitnesses[i] = algorithm.run().fitness;
        roundsInIterations[i] = ((NetPso) algorithm).totalIterationsInRepulsive;
        repulsiveCycles[i] = ((NetPso) algorithm).repulsiveCycles;
        gbestValues[i] = ((NetPso) algorithm).gbestValues;
      }

      //            System.out.println("--------------------------------------------------");
      //        printAlgorithmName(algorithm);
      printStats(fitnesses);
      System.out.println(
          "Avg rounds in repulsive;" + IntStream.of(roundsInIterations).average().getAsDouble());
      System.out.println(
          "Avg repulsive cycles;" + IntStream.of(repulsiveCycles).average().getAsDouble());
      StringBuilder builder = new StringBuilder();
      builder.append("gBest in every 100th CF evalution;");
      for (int i = 0; i < 1000; i++) {
        double avg = 0.0;
        for (int r = 0; r < reps; r++) {
          avg += gbestValues[r][i];
        }
        builder.append(avg / reps).append(";");
      }
      System.out.println(builder.toString());
      //            System.out.println("" + String.join(";", DoubleStream.of(((NetPso)
      // algorithm).gbestValues).mapToObj(String::valueOf).collect(Collectors.toList())));
    }
  }
Beispiel #11
0
 public static int sumOfEvenSquares(int[] a) {
   return IntStream.of(a).filter(x -> x % 2 == 0).map(x -> x * x).sum();
 }
  public void run_timewindow(String rootFolder, String filename) throws IOException {
    System.out.println(filename);
    long startTime = System.currentTimeMillis();
    // R
    // String[] elements = filename.split("_", -1);
    ArrayList<Integer> R_list = new ArrayList<Integer>();
    int day = Integer.parseInt(filename.substring(8, 10));
    int length = Integer.parseInt(filename.split("_", -1)[1]);
    IntStream.range(day, day + length).forEach(R_list::add);
    int[] R = ArrayUtils.toPrimitive(R_list.toArray(new Integer[0]));

    // lambdas
    BufferedReader br =
        new BufferedReader(new FileReader(rootFolder + filename.replace("graph", "lambda")));
    String line = br.readLine();
    JSONObject obj = new JSONObject(line.trim());
    ArrayList<Double> lambdas_list = new ArrayList<Double>();
    Iterator<?> keys = obj.keys();
    while (keys.hasNext()) {
      String key = (String) keys.next();
      lambdas_list.add(obj.getDouble(key));
    }
    double[] lambdas = lambdas_list.stream().mapToDouble(d -> d).toArray();
    br.close();

    // word dictionary
    BufferedReader br2 =
        new BufferedReader(new FileReader(rootFolder + filename.replace("graph", "index")));
    String line2 = br2.readLine();
    JSONObject word_dict = new JSONObject(line2.trim());
    br2.close();

    // edges and c
    APDMInputFormat apdm = new APDMInputFormat(new File(rootFolder + filename));
    ArrayList<Integer[]> edges = new ArrayList<Integer[]>(); // 1. graph G, input parameter G
    for (int[] edge : apdm.inputData.edges.keySet()) {
      edges.add(new Integer[] {edge[0], edge[1]});
    }
    double[] c = apdm.getPValue();
    double[] c2 = new double[c.length];
    for (int i = 0; i < c.length; i++) {
      c2[i] = c[i];
    }

    // detect only up or down
    if (this.up_down.equals("down")) {
      for (int i = 0; i < c.length; i++) {
        if (c2[i] > lambdas[i]) {
          c2[i] = lambdas[i];
        }
      }
    } else if (this.up_down.equals("up")) {
      for (int i = 0; i < c.length; i++) {
        if (c2[i] < lambdas[i]) {
          c2[i] = lambdas[i];
        }
      }
    }

    if (!this.is_first_time) {
      for (String iw : this.ignore_words) {
        for (int i = 0; i < apdm.numNodes; i++) {
          if (word_dict.getString(String.valueOf(i)).equals(iw)) {
            c2[i] = lambdas[i];
          }
        }
      }
    }

    // sparsity s
    // int s = apdm.trueSubGraphNodes.length ;
    int s = 8;

    GraphModelIHT graphModelIHT =
        new GraphModelIHT(
            edges, null, c2, null, s / 2, 1, s - 1 + 0.0D, 10, false, null, null, null, R, lambdas);
    // post-process
    List<Integer> index_list =
        IntStream.of(graphModelIHT.resultNodes_Tail).boxed().collect(Collectors.toList());
    List<String> words = new ArrayList<String>();
    List<Double> weights = new ArrayList<Double>();
    for (Integer a : index_list) {
      words.add(word_dict.getString(String.valueOf(a)));
      weights.add(c[a]);
    }
    ArrayList<String[]> sub_edges = new ArrayList<String[]>();
    for (Integer[] e : edges) {
      if (index_list.contains(e[0])
          && index_list.contains(e[1])
          && !word_dict
              .getString(String.valueOf(e[0]))
              .equals(word_dict.getString(String.valueOf(e[1])))) {
        sub_edges.add(
            new String[] {
              word_dict.getString(String.valueOf(e[0])), word_dict.getString(String.valueOf(e[1]))
            });
      }
    }
    if (graphModelIHT.funcValue > this.max_score) {
      this.max_score = graphModelIHT.funcValue;
      this.best_subgraph = graphModelIHT.resultNodes_Tail;
      this.temp_words = words;
      this.bestWindow = filename;
      this.subgraph = sub_edges;
      this.weights = weights;
    }
    long endTime2 = System.currentTimeMillis();
    System.out.println(String.valueOf(endTime2 - startTime));
  }
Beispiel #13
0
 // method to remove the duplicate elements from the integer array using lambda
 private Collection<Integer> removeDupInIntArrayUsingLambda() {
   List<Integer> intArrayList = IntStream.of(randomIntegers).boxed().collect(Collectors.toList());
   return selectDistinct(intArrayList);
 }
Beispiel #14
0
 @GenerateMicroBenchmark
 public int serialArray() {
   return IntStream.of(array).sum();
 }
Beispiel #15
0
 @GenerateMicroBenchmark
 public int array() {
   return IntStream.of(array).parallel().sum();
 }