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", ";"));
}
難道我拉伸推理規則太遠?這怎麼解決?
這就是一個!我有一種感覺,就是那樣的愚蠢。 – OldCurmudgeon
請參閱[避免原始類型](http://www.javapractices.com/topic/TopicAction.do?Id=224)。 – OldCurmudgeon