Chapter 5. Working with Records
Java 14 introduced a new type of data structure as a preview1 feature, which was finalized two releases later: Records. They are not just another typical Java type or technique you can use. Instead, Records are a completely new language feature providing you with a simple but feature-rich data aggregator with minimal boilerplate.
Data Aggregation Types
From a general point of view, data aggregation is the process of gathering data from multiple sources and assembling it in a format that better serves the intended purpose and more preferable usage. Perhaps the most well-known kind of data aggregation type is tuples.
Tuples
Mathematically speaking, a tuple is a “finite ordered sequence of elements.” In terms of programming languages, a tuple is a data structure aggregating multiple values or objects.
There are two kinds of tuples. Structural tuples rely only on the order of the contained elements and are therefore accessible only via their indices, as seen in the following Python2 code:
apple
=
(
"apple"
,
"green"
)
banana
=
(
"banana"
,
"yellow"
)
cherry
=
(
"cherry"
,
"red"
)
fruits
=
[
apple
,
banana
,
cherry
]
for
fruit
in
fruits
:
"The"
,
fruit
[
0
],
"is"
,
fruit
[
1
]
Nominal tuples don’t use an index to access their data but use component names instead, as seen in the following Swift code:
typealias
Fruit
=
(
name
:
String
,
color
:
String
)
let
fruits
:
[
Fruit
]
=
[
(
name
:
"apple"
,
color
:
"green"
),
(
name
:
"banana"
,
color
:
"yellow"
),
(
name
:
"cherry"
,
color
:
Get A Functional Approach to Java now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.