r/learnjava • • 9d ago

Don't understand "string":"string" syntax

A training example (https://codingbat.com/prob/p197888) uses the following method body:

public Map<String, String> mapBully(Map<String, String> map) {

}

and gives example calls like:

mapBully({"a": "candy", "b": "dirt"}) โ†’ {"a": "", "b": "candy"}

mapBully({"a": "candy"}) โ†’ {"a": "", "b": "candy"}

AFAIK, {x, y} produces an array; how does {"a":"candy","b":"dirt"} produce a Map<String,String>?

13 Upvotes

10 comments sorted by

1

u/AutoModerator 9d ago
Moderator Announcement Read More ยป

14

u/ZacPack 9d ago

Its just giving an example of the expected output based on the map parameter passed in. It's not syntax, rather just saying {"key1":"value1", "key2":"value2"}.

2

u/prehensilemullet 8d ago

Oh damn, I was thinking, finally Java has a reasonable Map literal syntax?

4

u/Emotional-End-5610 9d ago

Hey, the {x, y} syntax is often used informally to represent map/dictionary-like objects. So when someone gives an example of {"a": "b", "c": "d"} it is often just illustrating the contents of a map. In Java this sort of syntax isn't valid to represent a map but in languages like Python it is. The person who created that example just wasn't clear about that. You're right though, that {} example you gave is not a valid map literal in Java.

3

u/bowbahdoe 9d ago

What the others is saying is right. If you wanted it to actually work you would do

mapBully(Map.of("a", "candy", "b", "dirt"));

2

u/JoshuaTheProgrammer 8d ago

Be aware this only supports up to 10 key/value pairs and produces an immutable map, which may not be desired.

2

u/vegan_antitheist 9d ago

That's pseudocode. It doesn't compile. The whole point is that you write code that does compile.

1

u/8dot30662386292pow2 9d ago

In python and some others that would be used to initialize hashmap-like objects.

→ More replies (1)