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.

JavaCli Tooling

Code

snippet
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

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 =`.