Uno scrittoio digitale …

29 dicembre 2016

NPE Java8 Stream

Archiviato in: code — Tag:, , — admin @ 17:40

Volendo convertire una lista in una mappa … c’è un metodo sicuramente sbagliato:

	final Map data = new HashMap<>();
	data.put(1, "uno");

	System.out.println("1.");
	System.out.println(
		IntStream.rangeClosed(1, 2).boxed()
			.collect(
				HashMap::new,
				(map, i) -> map.put(i, data.get(i)),
				HashMap::putAll
			)
	);

	System.out.println("2.");
	//questa implementazione si basa sul metodo HashMap.merge (che lancia exception)
	System.out.println(
		IntStream.rangeClosed(1, 2).boxed()
			.collect(Collectors.toMap(
				i -> i, i -> data.get(i)
			))
	);

ottengo a console:

1.
{1=uno, 2=null}
2.
Exception in thread "main" java.lang.NullPointerException
	at java.util.HashMap.merge(HashMap.java:1224)
	at java.util.stream.Collectors.lambda$toMap$58(Collectors.java:1320)
	at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
	at java.util.stream.IntPipeline$4$1.accept(IntPipeline.java:250)
	at java.util.stream.Streams$RangeIntSpliterator.forEachRemaining(Streams.java:114)
	at java.util.Spliterator$OfInt.forEachRemaining(Spliterator.java:693)
	at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:481)
	at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:471)
	at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
	at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
	at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
	at com.contactlab.at.Errors.main(Errors.java:28)

Funziona con WordPress