2017-08-27 97 views
0

我想将字符串行转换为长数字。 我这样做:流减少错误地使用长型

String line = "eRNLpuGgnON"; 
char[] chars = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890-_".toCharArray(); 
Map<Character, Integer> charToInt = 
      IntStream.rangeClosed(0, chars.length - 1) 
        .boxed() 
        .collect(Collectors 
          .toMap(i -> (chars[i]), i -> i)); 

long l = line.chars() 
      .mapToObj(i -> (char) i) 
      .map(charToInt::get) 
      .reduce((int) 0L, ((a, b) -> a * chars.length + b)); 
System.out.println(l); 

我采取相应的指标在地图上用符号和执行乘法和加法的操作最短。

例子。我有一条线eRNLpuGgnON。这些符号在Map有这样的价值观:

e=2 
R=29 
N=50 
.... 

的算法非常简单:

0*64+2 = 2 
2*64 + 29 = 157 
157*64 + 50 = 10098 
........ 

最后,我需要得到这个值:

2842528454463293618 

,但我得到此值:

-1472624462 

而且,如果line的值足够短,则一切正常。我无法理解为什么Long没有正确的工作。

+1

你的降价幅度不是[关联](https://docs.oracle.com/javase/8/docs/api/java/util/stream/包summary.html#关联性)。 – shmosel

+0

@shmosel,我该如何解决它? –

回答

1

问题是您在reduce操作中使用整数,因此您达到Integer.MAX_VALUE会给出错误结果。在charToInt地图使用长的路要走:

Map<Character, Long> charValues = IntStream.range(0, chars.length) 
       .boxed() 
       .collect(Collectors.toMap(i -> chars[i], Long::valueOf)); 

long l = line.chars() 
     .mapToObj(i -> (char) i) 
     .map(charValues::get) 
     .reduce(0L, (a, b) -> a * chars.length + b); 

System.out.println(l); 
// prints "2842528454463293618"