Why can’t I map integers to strings when streaming from an array?

Arrays.stream(int[]) creates an IntStream, not a Stream<Integer>. So you need to call mapToObj instead of just map, when mapping an int to an object. This should work as expected: String commaSeparatedNumbers = Arrays.stream(numbers) .mapToObj(i -> ((Integer) i).toString()) //i is an int, not an Integer .collect(Collectors.joining(“, “)); which you can also write: String commaSeparatedNumbers = Arrays.stream(numbers) … Read more

Collect successive pairs from a stream

The Java 8 streams library is primarily geared toward splitting streams into smaller chunks for parallel processing, so stateful pipeline stages are quite limited, and doing things like getting the index of the current stream element and accessing adjacent stream elements are not supported. A typical way to solve these problems, with some limitations, of … Read more

When should I use streams?

Your assumption is correct. Your stream implementation is slower than the for-loop. This stream usage should be as fast as the for-loop though: EXCLUDE_PATHS.stream() .map(String::toLowerCase) .anyMatch(path::contains); This iterates through the items, applying String::toLowerCase and the filter to the items one-by-one and terminating at the first item that matches. Both collect() & anyMatch() are terminal operations. … Read more

How to find maximum value from a Integer using stream in Java 8?

You may either convert the stream to IntStream: OptionalInt max = list.stream().mapToInt(Integer::intValue).max(); Or specify the natural order comparator: Optional<Integer> max = list.stream().max(Comparator.naturalOrder()); Or use reduce operation: Optional<Integer> max = list.stream().reduce(Integer::max); Or use collector: Optional<Integer> max = list.stream().collect(Collectors.maxBy(Comparator.naturalOrder())); Or use IntSummaryStatistics: int max = list.stream().collect(Collectors.summarizingInt(Integer::intValue)).getMax();

Why does findFirst() throw a NullPointerException if the first element it finds is null?

The reason for this is the use of Optional<T> in the return. Optional is not allowed to contain null. Essentially, it offers no way of distinguishing situations “it’s not there” and “it’s there, but it is set to null“. That’s why the documentation explicitly prohibits the situation when null is selected in findFirst(): Throws: NullPointerException … Read more

Java 8 lambda get and remove element from list

To Remove element from the list objectA.removeIf(x -> conditions); eg: objectA.removeIf(x -> blockedWorkerIds.contains(x)); List<String> str1 = new ArrayList<String>(); str1.add(“A”); str1.add(“B”); str1.add(“C”); str1.add(“D”); List<String> str2 = new ArrayList<String>(); str2.add(“D”); str2.add(“E”); str1.removeIf(x -> str2.contains(x)); str1.forEach(System.out::println); OUTPUT: A B C

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)