Menu
CoddyTech

Final: Go Ledger

Lesson 47 of 48 in Coddy's Java for Go Developers course.

challenge icon

Challenge

Easy

Input is zero or more name quantity rows. Names are lowercase ASCII letters and quantities signed integers. Aggregate each name, discard totals at most zero, and return alphabetically sorted name:total lines; if none remain, return empty. All intermediate totals fit int.

Return the exact result text without a final newline from Exercise.solve(List<String> input). The visible locked Main.java reads all input lines and prints the returned text with one final newline. Do not print inside editable methods. All integers and arithmetic results fit Java int unless stated otherwise.

Editable files: Exercise.java, Text.java. Text.java supplies reusable parsing and formatting helpers. All files are in the unnamed package and compile together. Main.java is the only entry point and cannot be edited.

Port the following Go reference algorithm into the required Java implementation. Preserve aggregation, sorted names, and removal of nonpositive totals. The companion source program was executed against the same five input fixtures.

package main
import (
    "bufio"
    "fmt"
    "os"
    "sort"
)
func main() {
    totals:=map[string]int{}
    scanner:=bufio.NewScanner(os.Stdin)
    for scanner.Scan() {
        var name string
        var quantity int
        if _,err:=fmt.Sscanf(scanner.Text(),"%s %d",&name,&quantity);err!=nil { panic(err) }
        totals[name]+=quantity
    }
    if err:=scanner.Err();err!=nil { panic(err) }
    keys:=[]string{}
    for name,total:=range totals { if total>0 { keys=append(keys,name) } }
    sort.Strings(keys)
    if len(keys)==0 { fmt.Println("empty");return }
    for _,name:=range keys { fmt.Printf("%s:%d\n",name,totals[name]) }
}

Try it yourself

import java.io.*;
import java.util.*;
public class Main {
    private static void check(boolean condition) {
        if (!condition) throw new AssertionError("Required public API behavior failed");
    }
    public static void main(String[] args) throws Exception {
        List<String> input = new ArrayList<>();
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = reader.readLine()) != null) input.add(line);
        
        System.out.println(Exercise.solve(input));
    }
}

All lessons in Java for Go Developers

Practice on your own: Online Java compiler