0

I have a list of Strings in exact strict order, which I need to convert to a Map, where key is always going to be an even index, starting from 0 and value is going to be the next element, so list is going to look something like this: [key,value,key,value]. By condition my list has fixed even size, but just to handle case where there is no pair either key or value may be null. It is easy to achieve using standard for loop and put elements based on if condition.

But I am looking for more sophisticated (and short) way to achieve that. Maybe there is some option to group elements by two, and than put them into map as key and value correspondingly. Or maybe some existing solution.

I am grateful for any help.

Here is a piece of code I work with:

Resource resourceFile = applicationContext.getResource(ALPHA2_MAPPING_CSV);

    var csvRows = CSVReaderUtil.parseFromCSV(resourceFile);

    var alpha3AndAlpha2List = csvRows
        .stream()
        .flatMap(row -> row.getCells().stream())
        .filter(cell -> cell.getHeader().equals("Alpha-2 code") || cell.getHeader().equals("Alpha-3 code"))
        .toList();
nbond
  • 1
  • The dupe describes how to construct a "Pair", substitute that for "Map.Entry". – Andy Turner Jan 04 '23 at 14:19
  • The following is probably the sort of thing you should use (at least as the basis): `public class Alphas { private String alpha2; private String alpha3; }` – g00se Jan 04 '23 at 14:20
  • "But I am looking for more sophisticated (and short) way to achieve that" why do you need something sophisticated: `for (int i = 0; i < list.length(); i += 2) map.put(list.get(i), list.get(i+1));` is pretty simple and short. – Andy Turner Jan 04 '23 at 14:21

0 Answers0