dans mon Java code> Code J'ai une carte de hachage vide:
if (array == null || array.length == 0){
LOG.warn("Path is empty");
}
if (array.length == 1){
map.put("one", array[0]);
} else if (array.length == 2) {
map.put("one", array[0]);
map.put("two", array[1]);
} else if (array.length == 3) {
map.put("one", array[0]);
map.put("two", array[1]);
map.put("three", array[2]);
}
3 Réponses :
Vous pouvez vérifier null de la matrice avant cette ci-dessous codes
String[] keys = {"one", "two", "string"}; for(int = 0; i < array.length;i++){ map.put(keys[i], array[i]); }
private static final String[] numNames = { "", " one", " two", " three", " four", " five", " six", " seven", " eight", " nine", " ten", " eleven", " twelve", " thirteen", " fourteen", " fifteen", " sixteen", " seventeen", " eighteen", " nineteen" }; private static String[] array = new String[]{"1","2"}; private static Map<String, String> map = new HashMap<>(); public static void main(String[] args) { for(int i = 0; i < array.length; i++){ map.put(numNames[i], array[i]); } }
Qu'est-il arrivé quand "Array.Length" est supérieur à 20?
Comme il est étiqueté avec Java 8, vous avez ici une réponse en streaming, même si lors de l'accès à des indices, la boucle pour la boucle est probablement plus facile à lire (très subjective)
Utilisez également un LinkedHashMap de manière à ce que lorsque vous ithétiez les entrées, vous obtenez l'ordre d'insertion.