3

What could be the java equivalent code for following php syntax:

   $newPerson = array(
        'firstname'  => 'First',
        'lastname'   => 'Last',
        'email'      => 'test@example.com',
    );

I think here firstname is index of array and First is value at that index.How can I define such an array in java?

Harry Joy
  • 58,650
  • 30
  • 162
  • 207

5 Answers5

2

I suspect the closest you'll come is a map:

Map<String, String> map = new HashMap<String, String>();
map.put("firstname", "First");
map.put("lastname", "Last");
map.put("email", "test@example.com");

EDIT: If you want to preserve insertion order (i.e. you need to know that firstname was added before lastname) then you might want to use LinkedHashMap instead.

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
2

newPerson would be a java hash map (java.util.HashMap<String,String>) and you would explicitly insert by using put

Foo Bah
  • 25,660
  • 5
  • 55
  • 79
2
Map<String, String> newPerson = new HashMap<String, String>();
newPerson.put("firstname", "First");
newPerson.put("lastname", "Last");
newPerson.put("email", "test@example.com");
Foo Bah
  • 25,660
  • 5
  • 55
  • 79
Petar Ivanov
  • 91,536
  • 11
  • 82
  • 95
1
Map<String, String> newPerson = new HashMap<String, String>()
{{
    put("firstname", "First");
    put("lastname", "Last");
    put("email", "test@example.com");
}};
Eng.Fouad
  • 115,165
  • 71
  • 313
  • 417
0

You should also use SortedMap to store value with user-define index name in sorted order
here is sample code to do this
define a SortedMap with:

SortedMap<String, String>newPerson = new TreeMap<String, String>();

to put value in shorted-map used:
newPerson.put("firstname", "First");

and to get this value :
newPerson.get(""firstname");

Yagnesh Agola
  • 4,556
  • 6
  • 37
  • 50