2

I have this code to retrieve map's key value pair:

countries = BeneficiaryJSONParser.parseCountriesFeed(result);
for(Map.Entry<String, Object> entry: countries.entrySet()) {
    System.out.println(entry.getKey() + " : " + entry.getValue());
}

OUTPUT:

data : [{234=United Arab Emirates, 103=India, 210=Sri Lanka, 235=United Kingdom, 216=Switzerland, 200=Singapore, 76=France}]
status : 200
code : 1

I want to get data as an array with key and value. Because, I want to put those key-value pairs in,

final MyData items[] = new MyData[3];
items[0] = new MyData( "234","United Arab Emirates" );
items[1] = new MyData( "103","India" );
items[2] = new MyData( "210","Sri Lanka" );
.
.
. 
RNK
  • 5,582
  • 11
  • 65
  • 133
  • 2
    And what JSON library are you using? Why don't you deserialize it into a POJO? – fge Dec 15 '14 at 18:13
  • Possible duplicate of http://stackoverflow.com/questions/46898/iterate-over-each-entry-in-a-map – mirvine Dec 15 '14 at 19:16
  • @itrollin98 : actually the question is not to iterate all entries in `Map`. It's something I need to iterate `data` (described in output) – RNK Dec 15 '14 at 19:37

1 Answers1

4

You just need to convert each entry into a MyData:

List<MyData> data = new ArrayList<> ();
for (Map.Entry<String, Object> e: countries.entrySet()) {
  data.add(new MyData(e.getKey(), String.valueOf(e.getValue());
}

final MyData[] items = data.toArray(new MyData[0]);

Or using streams:

final MyData[] items = countries.entrySet().stream()
                        .map(e -> new MyData(e.getKey(), String.valueOf(e.getValue()))
                        .toArray(MyData[]::new);
assylias
  • 321,522
  • 82
  • 660
  • 783
  • It's giving me `[data, status, code]` when I tried with `System.out.println(Arrays.toString(items));` I need the country list within `data` object – RNK Dec 15 '14 at 18:20
  • I'm not sure I understand what you want that is not covered by my suggested solution. – assylias Dec 15 '14 at 22:53