Creating JavaFX sequences in Java programs

The last article explained, how sequences are represented in the runtime and touched some of the possibilities to create new JavaFX sequences in Java programs. This article and the follow-up will focus on sequence-creation and give an overview of additional possibilities.

The helper-class Sequences

The helper class Sequences in the package com.sun.javafx.runtime.sequence provides a number of methods to create sequences. Most of them have also been presented in the last article.

The methods can be divided in two groups. The first group are distinct factory methods. They create a new sequence from some kind of elements-list:

  • make() – Creates a sequence from a java.util.List, a part of an array or from explicitly listed elements.
  • fromArray() – Creates a sequence from the elements of an array.
  • fromCollection – Creates a new sequence with the elements of a given Collection. Since the elements of a Collection are unordered there is no guarantee about the order in the sequence.
  • range / rangeExclusive() – Creates sequences, which represent Integer- or Number-intervals.
  • singleton – Creates a sequence with a single element.
  • emptySequence() – Creates an empty sequence.

The second group alters an existing sequence. As sequences are implemented immutable, a new sequence is created and returned.

  • concatenate() – Creates a new sequence by concatenating sequences.
  • filter() – Creates a new sequence by masking out some of the elements of a sequence.
  • reverse – Creates a new sequence by reversing the order of a sequence.
  • subsequence – Creates a sequence, which is a fragment of a sequence.
  • upcast – Creates a new sequence by upcasting the elements of a sequence.
  • map – Creates a sequence which one would get after applying a mapping-function to the elements of a sequence. The mapping-function must be defined by implementing the interface SequenceMapper, which is also part of the package com.sun.javafx.runtime.sequence.
  • sort – Creates a new sequence by sorting the elements of a given sequence. The order can be induced either by the natural order of the elements, if they implement java.util.Comparable, or by providing a java.util.Comparator of the elements.

The class SequenceBuilder

The SequenceBuilder in the package com.sun.javafx.runtime.sequence provides a convenient way to create sequences incrementally. It is similar to the class StringBuilder, which creates Strings.

An instance of SequenceBuilder can only create one sequence at a time. It starts with an empty sequence to which elements are appended by calling one of its add()-methods. The result can be extracted by calling the method toSequence().