4
votes

Conversion d'une chaîne en Map dans Java 8

Quelqu'un peut-il me guider sur la façon de réaliser les objectifs ci-dessous en utilisant Java 8. Je ne sais pas comment obtenir ce compteur comme clé

String str = "abcd";

Map<Integer,String> map = new HashMap<>();

String[] strings = str.split("");

int count =0;
for(String s:strings){
    map.put(count++, s);// I want the counter as the key
}


2 commentaires

Copie possible de Java 8: Comment convertir une chaîne en carte ?


Vous recherchez de préférence une Map accédant qui est à nouveau principalement accessible via String.charAt . Quel est le cas d'utilisation de la création de cette carte si vous pouviez partager les détails?


4 Réponses :


4
votes

Vous pouvez utiliser IntStream pour effectuer cette opération. Utilisez la valeur entière comme clé et la valeur appropriée dans le tableau de chaînes à cet index comme valeur de la carte.

Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
    .boxed()
    .collect(Collectors.toMap(Function.identity(), i -> str.charAt(i) + "")); 

Une autre alternative qui évite le besoin de fractionner code> serait,

Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
    .boxed()
    .collect(Collectors.toMap(Function.identity(), i -> strings[i]));


0 commentaires

1
votes

Vous pouvez le faire sans le compteur comme:

for(String s: strings) {
     map.put(map.size(), s);
 }

Une autre façon de contourner , crédit @ Holger

String str = "abcd";
Map<Integer,String> map = new HashMap<>();
String[] strings = str.split("");
for(int i=0;i<strings.length;i++) {
    map.put(i, strings[i]);
}
map.forEach((k,v)->System.out.println(k+" "+v));


2 commentaires

ou pour (String s: strings) map.put (map.size (), s);


@Holger, ouais ça marchera, je l'ai ajouté à la réponse.



1
votes

Vous pouvez écrire comme

    String str = "abcd";
    Map<Integer, Character> map = IntStream.range(0, str.length()).boxed()
        .collect(Collectors.toMap(Function.identity(), pos -> str.charAt(pos)));

Pas besoin de diviser la chaîne avec String [] strings = str.split (""); Un simple one-liner .


0 commentaires

0
votes

Il existe de nombreuses solutions: certaines d'entre elles seraient comme ceci:

int count =0;
for (Character c:str.toCharArray()) {
  map.putIfAbsent(count++,c);
}

ou même utiliser un simple forEach

Map<Integer,Character> map = new HashMap<>();

AtomicInteger atomicInteger = new AtomicInteger(0); 
map = str.chars()
            .mapToObj(i->new AbstractMap.SimpleEntry<>(atomicInteger.getAndAdd(1),(char)i))
            .collect(Collectors.toMap(Map.Entry::getKey,Map.Entry::getValue));


0 commentaires