RAS
RAS

Reputation: 197

Char array to Map using Stream

I've a char array:

private char[] chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890-_".toCharArray();

I want get a Map when key is char symbol and value is index this char in array. Like this:

{q=0, w=1,....}

I want use a Stream api:

Map<Character, Integer> charToInt = IntStream.rangeClosed(0, chars.length)

But I do not understand what to do next

Upvotes: 0

Views: 3243

Answers (3)

Ervin Szilagyi
Ervin Szilagyi

Reputation: 16775

If you want to go with IntStream:

Map<Character, Integer> charToInt = 
                    IntStream.rangeClosed(0, chars.length-1)
                             .mapToObj(i -> Integer.valueOf(i)))
                             .collect(Collectors
                                      .toMap(i -> Character.valueOf(chars[i]), i -> i));

Upvotes: 1

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

P.S. We have previous similar answer as I was writing my own. But I keep it as alternative, using Pair class.

To solve this problem, you have to implement Pair class or use any available implementation (as example I give you easiest one):

final class Pair {
    private char ch;
    private int pos;

    public Pair(char ch, int pos) {
        this.ch = ch;
        this.pos = pos;
    }

    public char getChar() {
        return ch;
    }

    public int getPos() {
        return pos;
    }
}

Then you could use streams to solve your problem:

Map<Character, Integer> res = IntStream.range(0, chars.length)
         .mapToObj(pos -> new Pair(chars[pos], pos))
         .collect(Collectors.toMap(Pair::getChar, Pair::getPos));

Upvotes: 1

azro
azro

Reputation: 54148

You can go by this way and use the String instead of its charArray :

private String s = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890-_";

And then create the Map like this :

Map<Character, Integer> charToInt = s.chars()
                                     .mapToObj(i -> (char) i)
                                     .collect(Collectors.toMap(c -> c, c -> s.indexOf(c)));

So create a Map wit as key the char, and as value its index in the String

Upvotes: 1

Related Questions