接受的答案对我不起作用,因为 没有提供单参数方法。IntStream
collect
然而,要从收集器中受益,您必须首先将基元打包到对象中。如果要保留元素顺序,请使用 的扩展版本,如下所示:toMap
int
Integer
toMap
LinkedHashMap::new
package learning.java8;
import static java.util.stream.Collectors.*;
import static org.junit.Assert.*;
import java.time.DayOfWeek;
import java.time.format.TextStyle;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Locale;
import java.util.Map;
import java.util.stream.IntStream;
import org.junit.Test;
public class IntStreamLT {
@Test
public void q30339679() {
final String[] shortNames = getDayOfWeekNamesInEnglish(TextStyle.SHORT);
final String[] longNames = getDayOfWeekNamesInEnglish(TextStyle.FULL);
final Map<String, String> days = IntStream.range(0, shortNames.length).boxed()
.collect(toMap(i -> shortNames[i], i -> longNames[i]));
System.out.println(days);
final Map<String, String> sorted = IntStream.range(0, shortNames.length).boxed()
.collect(toMap(
i -> shortNames[i], i -> longNames[i],
(i, j) -> i, LinkedHashMap::new));
System.out.println(sorted);
assertEquals("{Mon=Monday, Tue=Tuesday, Wed=Wednesday, Thu=Thursday, "
+ "Fri=Friday, Sat=Saturday, Sun=Sunday}", sorted.toString());
}
private static String[] getDayOfWeekNamesInEnglish(final TextStyle style) {
return Arrays.stream(DayOfWeek.values())
.map(day -> day.getDisplayName(style, Locale.ENGLISH))
.toArray(String[]::new);
}
}
另请参阅:为什么原始流没有 collect(Collector)?