Can someone please guide me on how to achieve the below using Java 8. I don't know how to get that counter as the key
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
}
You can use IntStream
to get this thing done. Use the integer value as the key, and the relevant value in the string array at that index as the value of the map.
Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> strings[i]));
Another alternative that obviates the need of split
would be,
Map<Integer, String> counterToStr = IntStream.range(0, strings.length)
.boxed()
.collect(Collectors.toMap(Function.identity(), i -> str.charAt(i) + ""));
You can do it without the counter as:
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));
Another way around , credit @Holger
for(String s: strings) {
map.put(map.size(), s);
}
You can write like
String str = "abcd";
Map<Integer, Character> map = IntStream.range(0, str.length()).boxed()
.collect(Collectors.toMap(Function.identity(), pos -> str.charAt(pos)));
No need to split the String with String[] strings = str.split("");
A simple one-liner.
There are many solution: some of them would be like this:
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));
or even use simple forEach
int count =0;
for (Character c:str.toCharArray()) {
map.putIfAbsent(count++,c);
}
This solution will help you to create a linked hash map. The keys are characters and the values are the count of each character in the string.
String str = "preethi";
Map<Character, Integer> lhm = new LinkedHashMap<>();
str.chars().mapToObj(x -> (char)x).forEach(ch -> {
lhm.put(ch, lhm.get(ch) != null ? lhm.get(ch) + 1: 1);
});
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.