0

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

1
  • 1
    In your case method like zipWithIndex would be useful. Unfortunately Java's streams don't support anything similar yet. Have a look on this question. It might give you a hint what to do. Commented Aug 26, 2017 at 19:44

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

1

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));

Comments

1

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));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.