Local Record Inside A Method
Declare a record inside a method to model intermediate results with methods and sorting, without widening the class-level API surface.
Code
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
public class LocalRecordInMethod {
public static void main(String[] args) {
List<String> channels = List.of("web", "mobile", "api");
int[] revenue = { 4800, 3100, 900 };
// 局部 record:字段、方法都可用,只在方法体内可见
record ChannelRevenue(String channel, int cents) {
double dollars() { return cents / 100.0; }
}
List<ChannelRevenue> rows = new ArrayList<>();
for (int i = 0; i < channels.size(); i++) {
rows.add(new ChannelRevenue(channels.get(i), revenue[i]));
}
rows.sort(Comparator.comparingInt(ChannelRevenue::cents).reversed());
rows.forEach(r -> System.out.println("channel: " + r.channel() + " $" + r.dollars()));
ChannelRevenue best = rows.get(0);
System.out.println("best = " + best.channel() + " $" + best.dollars());
}
}What the code does
All of the logic lives in the classes LocalRecordInMethod and ChannelRevenue and the function main.
The loop for (int i = 0; i < channels.size(); i++) is the only repeated construct.
Watch out for
- The project needs no additions before this runs.
Using it
Main surface, as written: public static void main(String[] args)
Look for the channel:, best = prefixes when the file runs; they tie each line to its step.
Key statements
rows.sort(Comparator.comparingInt(ChannelRevenue::cents).reversed());
double dollars() { return cents / 100.0; }
Interactive Tools for This Topic
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
FAQ
- What does Local Record Inside A Method print when run?
- Running the file directly is enough — expect labeled output lines such as `channel:`, `best =`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.