简体   繁体   中英

Get key value pair from Map

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" );
.
.
. 

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM