heyhey
heyhey

Reputation: 11

java map toString() override

System.out.println(map);

so result is {A=2, B=4, C=5 ..} but i want print

A 2
B 4
C 5
...

So, my processor's hint is map toSting() override, but i don't understand

this is my code

class MapManager2 {
public static Map<String, Double> readData(String fileName) {
    Map<String, Double> mapOfData;
    Map<String, Double> sortedByValue = null;

    try {
        Scanner file = new Scanner(new File(fileName)); // read file
        mapOfData = new TreeMap<>(); // create Map to store the values

        while (file.hasNextLine()) {
            String line = file.nextLine(); // read the line
            String[] words = line.split("\\s+"); // split the item and price by space
            Double price = Double.parseDouble(words[1]); // parse the double price
            mapOfData.put(words[0], price); // put the data in map
        }

        /* Sort the map on basis of value*/
        sortedByValue = mapOfData.entrySet()
                .stream().sorted((Map.Entry.<String, Double>comparingByValue()))
                .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e1, LinkedHashMap::new));
    } catch (FileNotFoundException e) {
        System.out.println("Input file not found");
    }
    return sortedByValue;
}

}
public class Problem21 {
public static void main(String[] args) {
    Map<String, Double> map = MapManager2.readData("input.txt");
    if (map == null) {
        System.out.println("Input file not found.");
        return;
    }
    System.out.println(map);
}

}

Upvotes: -2

Views: 3929

Answers (5)

Jesse
Jesse

Reputation: 1

A little improvement to the first answer.

Map<String, String> map = new HashMap<>() {
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        map.forEach((key, value) -> {
                    sb.append(key).append(": ");
                    sb.append(value).append(System.lineSeparator());
                }
        );
        return sb.toString();
    }
};

Upvotes: 0

DownloadPizza
DownloadPizza

Reputation: 3466

Your prof is telling you to override the toString method of the Map class. I think the best idea is an anonymous override.

Map<String, String> test = new HashMap<>() {
    @Override
    public String toString() {
        StringBuilder stb = new StringBuilder();
        for (Map.Entry<String, String> entry : this.entrySet()) {
            stb.append(entry.getKey()).append(" ")
                    .append(entry.getValue()).append("\n");
        }
        return stb.toString();
    }
};

Note that I don't have any way to chexk this code for errors right now, so you may have to fix some names.

Upvotes: 2

MNEMO
MNEMO

Reputation: 268

To override the toString() method, extend TreeMap class and replace your TreeMap instance with new class.

import java.util.Map;
import java.util.TreeMap;

public class MyTreeMap extends TreeMap<String,Double> {
    @Override
    public String toString() {
        StringBuilder result = new StringBuilder();
        this.entrySet().forEach(me -> {
            System.out.printf("%s %s%n", me.getKey(), me.getValue());
        });
        return result.toString();
    }
}

Upvotes: 0

rzwitserloot
rzwitserloot

Reputation: 102820

So, my processor's hint is map toSting() override, but i don't understand

I don't know who your 'processor' is (professor?), but that's a dumb hint.

overriding things makes sense when you're subclassing something. Don't subclass map, that's... not what you want.

instead of passing 'map' to System.out.println, which will result in println invoking .toString() on that object and printing the resulting string, make your own string:

String print = map.entrySet().stream()
    // convert each element in the map to the string "KEY VALUE"
    .map(x -> x.getKey() + " " + x.getValue())
    // collect em by joining em, separating each "KEY VALUE" string with a newline
    .collect(Collectors.joining("\n"));
System.out.println(print);

Upvotes: 1

sprinter
sprinter

Reputation: 27946

I'm not sure what you mean by "processor's hint" but you don't really need to override toString. Simpler is to just convert the map to the string you want:

map.entrySet().stream()
    .map(e -> e.getKey() + " " + e.getValue())
    .collect(Collectors.joining("\n"));

Or if you just want to print the map directly:

map.forEach((k, v) -> System.out.println(k + " " + v));

Upvotes: 0

Related Questions