2016-08-03 123 views
1

Divide two String into substrings and pair them并得到了这个。问题是Collectors.toList被拒绝,并不兼容的类型 -泛型类型推断不起作用?

/** 
* General pair of items. 
* 
* @param <P> - Type of the first item in the pair. 
* @param <Q> - Type of the second item. 
*/ 
static class Pair<P, Q> { 
    final P p; 
    final Q q; 

    public Pair(P p, Q q) { 
     this.p = p; 
     this.q = q; 
    } 

    @Override 
    public String toString() { 
     return "{" + p + "," + q + "}"; 
    } 
} 

/** 
* Gets the `n`th item is present in the array - otherwise returns null. 
* 
* @param a - The array 
* @param n - Which one in the array we want. 
* @param <T> - The type of the array entries. 
* @return - The `n`th entry in the array or null if not present. 
*/ 
private static <T> T n(T[] a, int n) { 
    return n < a.length ? a[n] : null; 
} 

/** 
* Pairs up each element in the arrays. 
* 
* @param ps - The `P` array. 
* @param qs - The `Q` array. 
* @param <P> - The type of the elements in the `P` array. 
* @param <Q> - The type of the elements in the `Q` array. 
* @return A list of `Pair`s of each element. 
*/ 
static <P, Q> List<Pair<P, Q>> pairUp(P[] ps, Q[] qs) { 
    return IntStream.range(0, Math.max(ps.length, qs.length)) 
      .mapToObj(i -> new Pair(n(ps, i), n(qs, i))) 
      .collect(Collectors.toList()); 
} 

/** 
* Splits the two strings on a separator and returns a list of Pairs of thje corresponding items. 
* 
* @param a   - The first string. 
* @param b   - The second string. 
* @param separator - The separator. 
* @return - A List of Paired up entries from `a` and `b`. 
*/ 
private static List<Pair<String, String>> fold(String a, String b, String separator) { 
    return pairUp(a.split(separator, -1), b.split(separator, -1)); 
} 

public void test() { 
    System.out.println(fold("1;2;3;4", "Value1;Value2;Value whitespace", ";")); 
} 

难道我拉伸推理规则太远?这怎么解决?

回答

7

添加钻石运营商Pair构造

new Pair<>(n(ps, i), n(qs, i)) 
+0

这就是一个!我有一种感觉,就是那样的愚蠢。 – OldCurmudgeon

+0

请参阅[避免原始类型](http://www.javapractices.com/topic/TopicAction.do?Id=224)。 – OldCurmudgeon