APIdia Launch Partner
Top Description Inners Fields Constructors Methods
java.text

public final Class ListFormat

extends Format
Class Inheritance
Imports
java.io.IOException, .ObjectInputStream, .Serial, java.util.Arrays, .List, .Locale, .Objects, java.util.stream.IntStream, sun.util.locale.provider.LocaleProviderAdapter

ListFormat formats or parses a list of strings in a locale-sensitive way. Use ListFormat to construct a list of strings displayed for end users. For example, displaying a list of 3 weekdays, e.g. "Monday", "Wednesday", "Friday" as "Monday, Wednesday, and Friday" in an inclusive list type. This class provides the functionality defined in Unicode Consortium's LDML specification for List Patterns.

Three formatting types are provided: STANDARD, OR, and UNIT, which determines the punctuation between the strings and the connecting words if any. Also, three formatting styles for each type are provided: FULL, SHORT, and NARROW, suitable for how the strings are abbreviated (or not). The following snippet is an example of formatting the list of Strings "Foo", "Bar", "Baz" in US English with STANDARD type and FULL style:

ListFormat.getInstance(Locale.US, ListFormat.Type.STANDARD, ListFormat.Style.FULL) .format(List.of("Foo", "Bar", "Baz"))
ListFormat.getInstance(Locale.US, ListFormat.Type.STANDARD, ListFormat.Style.FULL)
    .format(List.of("Foo", "Bar", "Baz"))
This will produce the concatenated list string, "Foo, Bar, and Baz" as seen in the following:
Formatting examples
FULL SHORT NARROW
STANDARD Foo, Bar, and Baz Foo, Bar, & Baz Foo, Bar, Baz
OR Foo, Bar, or Baz Foo, Bar, or Baz Foo, Bar, or Baz
UNIT Foo, Bar, Baz Foo, Bar, Baz Foo Bar Baz
Note: these examples are from CLDR, there could be different results from other locale providers.

Alternatively, Locale, Type, and/or Style independent instances can be created with getInstance(String[]). The String array to the method specifies the delimiting patterns for the start/middle/end portion of the formatted string, as well as optional specialized patterns for two or three elements. Refer to the method description for more detail.

On parsing, if some ambiguity is found in the input string, such as delimiting sequences in the input string, the result, when formatted with the same formatting, does not re-produce the input string. For example, a two element String list "a, b,", "c" will be formatted as "a, b, and c", but may be parsed as three elements "a", "b", "c".

Implementation Specification

This class is immutable and thread-safe

Since
22
External Specification
https://www.unicode.org/reports/tr35

Nested and Inner Type Summary

Modifier and TypeClass and Description
public static enum
ListFormat.Style

A ListFormat style - FULL, SHORT, and NARROW.

public static enum
ListFormat.Type

A ListFormat type - STANDARD, OR, and UNIT.

Field Summary

Modifier and TypeField and Description
private static final int
private transient String
private transient String
private final Locale
locale

The locale to use for formatting list patterns.

private static final int
private transient String
private static final int
private final String[]
patterns

The array of five pattern Strings.

private static final int
private static final long
private static final int
private transient String
private transient String
private static final int
private static final int

Constructor Summary

AccessConstructor and Description
private
ListFormat(Locale l, String[] patterns)

Method Summary

Modifier and TypeMethod and Description
private String
public boolean

Returns:

true if the specified object is equal to this ListFormat
equals
(Object
the object to be compared for equality.
obj
)

Overrides java.lang.Object.equals.

Compares the specified object with this ListFormat for equality.

private static int[]

Returns:

the start and end positions of the first pattern found in the given source starting at pos, or null if no such pattern exists
findPattern
(String
string to search
source
,
int
position at which to start the search
pos
,
String
starting string within the pattern
prefix
,
String
ending string within the pattern
suffix
)

Returns the start and end positions of the first pattern found in the given source starting at pos, or null if no such pattern exists.

private static int[]

Returns:

the positions of the "{0}", "{1}", and "{2}" placeholders in the given pattern string, or null if the pattern is invalid
findPlaceholders
(String
pattern string to parse
pattern
)

Returns the positions of the "{0}", "{1}", and "{2}" placeholders in the given pattern string, or null if the pattern is invalid.

public String

Returns:

the string that consists of the input strings, concatenated with the patterns of this ListFormat
format
(List<String>
The list of input strings to format. There should at least one String element in this list, otherwise an IllegalArgumentException is thrown.
input
)

Returns the string that consists of the input strings, concatenated with the patterns of this ListFormat.

public StringBuffer

Returns:

the string buffer passed in as toAppendTo, with formatted text appended
format
(Object
The object to format. Must be a List or an array of Object.
obj
,
StringBuffer
where the text is to be appended
toAppendTo
,
FieldPosition
Ignored. Not used in ListFormat. May be null
pos
)

Implements abstract java.text.Format.format.

Formats an object and appends the resulting text to a given string buffer.

pack-priv Format.StringBuf
private Format.StringBuf
format(Object obj, Format.StringBuf toAppendTo)

public AttributedCharacterIterator
formatToCharacterIterator(Object arguments)

Overrides java.text.Format.formatToCharacterIterator.

Formats an Object producing an AttributedCharacterIterator.

private MessageFormat
public static Locale[]

Returns:

the available locales that support ListFormat
getAvailableLocales
()

Returns the available locales that support ListFormat.

public static ListFormat

Returns:

the ListFormat object for the default FORMAT Locale, STANDARD type, and FULL style
getInstance
()

Returns the ListFormat object for the default FORMAT Locale, STANDARD type, and FULL style.

public static ListFormat

Returns:

the ListFormat object for the specified Locale, Type, and Style
getInstance
(Locale
Locale to be used, not null
locale
,
ListFormat.Type
type of the ListFormat. One of STANDARD, OR, or UNIT, not null
type
,
ListFormat.Style
style of the ListFormat. One of FULL, SHORT, or NARROW, not null
style
)

Returns the ListFormat object for the specified Locale, Type, and Style.

public static ListFormat

Returns:

the ListFormat object for the specified patterns
getInstance
(String[]
array of patterns, not null
patterns
)

Returns the ListFormat object for the specified patterns.

public Locale

Returns:

the Locale of this ListFormat
getLocale
()

Returns the Locale of this ListFormat.

public String[]

Returns:

the patterns used in this ListFormat
getPatterns
()

Returns the patterns used in this ListFormat.

public int
hashCode()

Overrides java.lang.Object.hashCode.

Returns a hash code value for this object.

private void
init()

public List<String>

Returns:

the parsed list of strings from the source string
parse
(String
the string to parse, not null.
source
)

Returns the parsed list of strings from the source string.

public Object

Returns:

A list of string parsed from the source. In case of error, returns null.
parseObject
(String
A string, part of which should be parsed.
source
,
ParsePosition
A ParsePosition object with index and error index information as described above.
parsePos
)

Implements abstract java.text.Format.parseObject.

Parses text from a string to produce a list of strings.

private void
public String

Returns:

a string identifying this ListFormat, for debugging
toString
()

Overrides java.lang.Object.toString.

Returns a string identifying this ListFormat, for debugging.

Inherited from java.text.Format:
clonecreateAttributedCharacterIteratorcreateAttributedCharacterIteratorcreateAttributedCharacterIteratorcreateAttributedCharacterIteratorformatparseObject

Field Detail

ENDback to summary
private static final int END
endAfterback to summary
private transient String endAfter
endBetweenback to summary
private transient String endBetween
localeback to summary
private final Locale locale

The locale to use for formatting list patterns.

MIDDLEback to summary
private static final int MIDDLE
middleBetweenback to summary
private transient String middleBetween
PATTERN_ARRAY_LENGTHback to summary
private static final int PATTERN_ARRAY_LENGTH
patternsback to summary
private final String[] patterns

The array of five pattern Strings. Each element corresponds to the Unicode LDML's `listPatternsPart` type, i.e, start/middle/end/two/three.

PLACEHOLDER_LENGTHback to summary
private static final int PLACEHOLDER_LENGTH
serialVersionUIDback to summary
private static final long serialVersionUID

Hides java.text.Format.serialVersionUID.

Annotations
@Serial
STARTback to summary
private static final int START
startBeforeback to summary
private transient String startBefore
startBetweenback to summary
private transient String startBetween
THREEback to summary
private static final int THREE
TWOback to summary
private static final int TWO

Constructor Detail

ListFormatback to summary
private ListFormat(Locale l, String[] patterns)

Method Detail

createMessageFormatStringback to summary
private String createMessageFormatString(int count)
equalsback to summary
public boolean equals(Object obj)

Overrides java.lang.Object.equals.

Compares the specified object with this ListFormat for equality. Returns true if the specified object is also a ListFormat, and locale and patterns, returned from getLocale() and getPatterns() respectively, are equal.

Parameters
obj:Object

the object to be compared for equality.

Returns:boolean

true if the specified object is equal to this ListFormat

Annotations
@Override
findPatternback to summary
private static int[] findPattern(String source, int pos, String prefix, String suffix)

Returns the start and end positions of the first pattern found in the given source starting at pos, or null if no such pattern exists. The pattern must contain at least one character between the prefix and suffix strings. The returned end position is exclusive.

Parameters
source:String

string to search

pos:int

position at which to start the search

prefix:String

starting string within the pattern

suffix:String

ending string within the pattern

Returns:int[]

the start and end positions of the first pattern found in the given source starting at pos, or null if no such pattern exists

findPlaceholdersback to summary
private static int[] findPlaceholders(String pattern)

Returns the positions of the "{0}", "{1}", and "{2}" placeholders in the given pattern string, or null if the pattern is invalid. The returned array contains -1 for "{2}" if that placeholder is absent.

Parameters
pattern:String

pattern string to parse

Returns:int[]

the positions of the "{0}", "{1}", and "{2}" placeholders in the given pattern string, or null if the pattern is invalid

formatback to summary
public String format(List<String> input)

Returns the string that consists of the input strings, concatenated with the patterns of this ListFormat.

API Note

Formatting the string from an excessively long list may exceed memory or string sizes.

Parameters
input:List<String>

The list of input strings to format. There should at least one String element in this list, otherwise an IllegalArgumentException is thrown.

Returns:String

the string that consists of the input strings, concatenated with the patterns of this ListFormat

Exceptions
IllegalArgumentException:
if the length of input is zero.
NullPointerException:
if input is null.
formatback to summary
public StringBuffer format(Object obj, StringBuffer toAppendTo, FieldPosition pos)

Implements abstract java.text.Format.format.

Formats an object and appends the resulting text to a given string buffer. The object should either be a List or an array of Objects.

API Note

Formatting the string from an excessively long list or array may exceed memory or string sizes.

Parameters
obj:Object

The object to format. Must be a List or an array of Object.

toAppendTo:StringBuffer

where the text is to be appended

pos:FieldPosition

Ignored. Not used in ListFormat. May be null

Returns:StringBuffer

the string buffer passed in as toAppendTo, with formatted text appended

Annotations
@Override
Exceptions
NullPointerException:
if obj or toAppendTo is null
IllegalArgumentException:
if obj is neither a List nor an array of Objects, or its length is zero.
formatback to summary
pack-priv Format.StringBuf format(Object obj, Format.StringBuf toAppendTo, FieldPosition pos)

Overrides java.text.Format.format.

Annotations
@Override
formatback to summary
private Format.StringBuf format(Object obj, Format.StringBuf toAppendTo)
formatToCharacterIteratorback to summary
public AttributedCharacterIterator formatToCharacterIterator(Object arguments)

Overrides java.text.Format.formatToCharacterIterator.

Doc from java.text.Format.formatToCharacterIterator.

Formats an Object producing an AttributedCharacterIterator. You can use the returned AttributedCharacterIterator to build the resulting String, as well as to determine information about the resulting String.

Each attribute key of the AttributedCharacterIterator will be of type Field. It is up to each Format implementation to define what the legal values are for each attribute in the AttributedCharacterIterator, but typically the attribute key is also used as the attribute value.

Annotations
@Override
generateMessageFormatback to summary
private MessageFormat generateMessageFormat(Object[] input)
getAvailableLocalesback to summary
public static Locale[] getAvailableLocales()

Returns the available locales that support ListFormat.

Returns:Locale[]

the available locales that support ListFormat

getInstanceback to summary
public static ListFormat getInstance()

Returns the ListFormat object for the default FORMAT Locale, STANDARD type, and FULL style.

Returns:ListFormat

the ListFormat object for the default FORMAT Locale, STANDARD type, and FULL style

getInstanceback to summary
public static ListFormat getInstance(Locale locale, ListFormat.Type type, ListFormat.Style style)

Returns the ListFormat object for the specified Locale, Type, and Style.

Parameters
locale:Locale

Locale to be used, not null

type:ListFormat.Type

type of the ListFormat. One of STANDARD, OR, or UNIT, not null

style:ListFormat.Style

style of the ListFormat. One of FULL, SHORT, or NARROW, not null

Returns:ListFormat

the ListFormat object for the specified Locale, Type, and Style

Exceptions
NullPointerException:
if any of the arguments are null
getInstanceback to summary
public static ListFormat getInstance(String[] patterns)

Returns the ListFormat object for the specified patterns.

This factory returns an instance based on the customized patterns array, instead of letting the runtime provide appropriate patterns for the Locale, Type, or Style.

The patterns array should contain five String patterns, each corresponding to the Unicode LDML's listPatternPart, i.e., "start", "middle", "end", two element, and three element patterns in this order. Each pattern contains "{0}" and "{1}" (and "{2}" for the three element pattern) placeholders that are substituted with the passed input strings on formatting. If the length of the patterns array is not 5, an IllegalArgumentException is thrown.

Each pattern string is first parsed as follows. Literals in parentheses, such as "start_before", are optional:

start := (start_before){0}start_between{1}
middle := {0}middle_between{1}
end := {0}end_between{1}(end_after)
two := (two_before){0}two_between{1}(two_after)
three := (three_before){0}three_between1{1}three_between2{2}(three_after)
If two or three pattern string is empty, it falls back to "(start_before){0}end_between{1}(end_after)", "(start_before){0}start_between{1}end_between{2}(end_after)" respectively. If parsing of any pattern string for start, middle, end, two, or three fails, it throws an IllegalArgumentException.

On formatting, the input string list with n elements substitutes above placeholders based on the number of elements:

n = 1: {0}
n = 2: parsed pattern for "two"
n = 3: parsed pattern for "three"
n > 3: (start_before){0}start_between{1}middle_between{2} ... middle_between{m}end_between{n}(end_after)
As an example, the following table shows a pattern array which is equivalent to STANDARD type, FULL style in US English:
Standard/Full Patterns in US English
Pattern Kind Pattern String
start "{0}, {1}"
middle "{0}, {1}"
end "{0}, and {1}"
two "{0} and {1}"
three ""
Here are the resulting formatted strings with the above pattern array.
Formatting examples
Input String List Formatted String
"Foo", "Bar", "Baz", "Qux" "Foo, Bar, Baz, and Qux"
"Foo", "Bar", "Baz" "Foo, Bar, and Baz"
"Foo", "Bar" "Foo and Bar"
"Foo" "Foo"
Parameters
patterns:String[]

array of patterns, not null

Returns:ListFormat

the ListFormat object for the specified patterns

Exceptions
IllegalArgumentException:
if the length patterns array is not 5, or any of start, middle, end, two, or three patterns cannot be parsed.
NullPointerException:
if patterns is null.
getLocaleback to summary
public Locale getLocale()

Returns the Locale of this ListFormat. The locale is defined by getInstance(Locale, Type, Style) or getInstance(String[]).

Returns:Locale

the Locale of this ListFormat

getPatternsback to summary
public String[] getPatterns()

Returns the patterns used in this ListFormat. The patterns are defined by getInstance(Locale, Type, Style) or getInstance(String[]).

Returns:String[]

the patterns used in this ListFormat

hashCodeback to summary
public int hashCode()

Overrides java.lang.Object.hashCode.

Doc from java.lang.Object.hashCode.

Returns a hash code value for this object. This method is supported for the benefit of hash tables such as those provided by java.util.HashMap.

The general contract of hashCode is:

  • Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified. This integer need not remain consistent from one execution of an application to another execution of the same application.
  • If two objects are equal according to the equals method, then calling the hashCode method on each of the two objects must produce the same integer result.
  • It is not required that if two objects are unequal according to the equals method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
Annotations
@Override
initback to summary
private void init()
parseback to summary
public List<String> parse(String source) throws ParseException

Returns the parsed list of strings from the source string. Note that format(List) and this method may not guarantee a round-trip, if the input strings contain ambiguous delimiters. For example, a two element String list "a, b,", "c" will be formatted as "a, b, and c", but may be parsed as three elements "a", "b", "c".

Parameters
source:String

the string to parse, not null.

Returns:List<String>

the parsed list of strings from the source string

Exceptions
ParseException:
if parse failed
NullPointerException:
if source is null
parseObjectback to summary
public Object parseObject(String source, ParsePosition parsePos)

Implements abstract java.text.Format.parseObject.

Parses text from a string to produce a list of strings.

The method attempts to parse text starting at the index given by parsePos. If parsing succeeds, then the index of parsePos is updated to the index after the last character used (parsing does not necessarily use all characters up to the end of the string), and the parsed object is returned. The updated parsePos can be used to indicate the starting point for the next call to parse additional text. If an error occurs, then the index of parsePos is not changed, the error index of parsePos is set to the index of the character where the error occurred, and null is returned. See the parse(String) method for more information on list parsing.

Parameters
source:String

A string, part of which should be parsed.

parsePos:ParsePosition

A ParsePosition object with index and error index information as described above.

Returns:Object

A list of string parsed from the source. In case of error, returns null.

Annotations
@Override
Exceptions
NullPointerException:
if source or parsePos is null.
IndexOutOfBoundsException:
if the starting index given by parsePos is outside source.
readObjectback to summary
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException
Annotations
@Serial
toStringback to summary
public String toString()

Overrides java.lang.Object.toString.

Returns a string identifying this ListFormat, for debugging.

Returns:String

a string identifying this ListFormat, for debugging

Annotations
@Override
java.text back to summary

public final Enum ListFormat.Style

extends Enum<ListFormat.Style>
Class Inheritance

A ListFormat style - FULL, SHORT, and NARROW.

Style is an enum which represents the style for formatting a list within a given ListFormat instance.

Since
22

Field Summary

Modifier and TypeField and Description
public static final ListFormat.Style
FULL

The FULL ListFormat style.

public static final ListFormat.Style
NARROW

The NARROW ListFormat style.

public static final ListFormat.Style
SHORT

The SHORT ListFormat style.

Constructor Summary

AccessConstructor and Description
private

Method Summary

Modifier and TypeMethod and Description
public static ListFormat.Style
public static ListFormat.Style[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

FULLback to summary
public static final ListFormat.Style FULL

The FULL ListFormat style. This is the default style, which typically is the full description of the text and punctuation that appear between the list elements. Suitable for elements, such as "Monday", "Tuesday", "Wednesday", etc.

NARROWback to summary
public static final ListFormat.Style NARROW

The NARROW ListFormat style. This style is typically the shortest description of the text and punctuation that appear between the list elements. Suitable for elements, such as "M", "T", "W", etc.

SHORTback to summary
public static final ListFormat.Style SHORT

The SHORT ListFormat style. This style is typically an abbreviation of the text and punctuation that appear between the list elements. Suitable for elements, such as "Mon", "Tue", "Wed", etc.

Constructor Detail

Styleback to summary
private Style()

Method Detail

valueOfback to summary
public static ListFormat.Style valueOf(String name)
valuesback to summary
public static ListFormat.Style[] values()
java.text back to summary

public final Enum ListFormat.Type

extends Enum<ListFormat.Type>
Class Inheritance

A ListFormat type - STANDARD, OR, and UNIT.

Type is an enum which represents the type for formatting a list within a given ListFormat instance. It determines the punctuation and the connecting words in the formatted text.

Since
22

Field Summary

Modifier and TypeField and Description
public static final ListFormat.Type
OR

The OR ListFormat type.

public static final ListFormat.Type
STANDARD

The STANDARD ListFormat type.

public static final ListFormat.Type
UNIT

The UNIT ListFormat type.

Constructor Summary

AccessConstructor and Description
private
Type()

Method Summary

Modifier and TypeMethod and Description
public static ListFormat.Type
public static ListFormat.Type[]
Inherited from java.lang.Enum:
clonecompareTodescribeConstableequalsfinalizegetDeclaringClasshashCodenameordinaltoStringvalueOf

Field Detail

ORback to summary
public static final ListFormat.Type OR

The OR ListFormat type. This type concatenates elements in "or" enumeration.

STANDARDback to summary
public static final ListFormat.Type STANDARD

The STANDARD ListFormat type. This is the default type, which concatenates elements in "and" enumeration.

UNITback to summary
public static final ListFormat.Type UNIT

The UNIT ListFormat type. This type concatenates elements, useful for enumerating units.

Constructor Detail

Typeback to summary
private Type()

Method Detail

valueOfback to summary
public static ListFormat.Type valueOf(String name)
valuesback to summary
public static ListFormat.Type[] values()