Filter values only if not null using lambda in Java8

I have a list of objects say car. I want to filter this list based on some parameter using Java 8. But if the parameter is null, it throws NullPointerException. How to filter out null values? Current code is as follows requiredCars = cars.stream().filter(c -> c.getName().startsWith(“M”)); This throws NullPointerException if getName() returns null. 6 Answers … Read more

How can I count occurrences with groupBy?

I want to collect the items in a stream into a map which groups equal objects together, and maps to the number of occurrences. List<String> list = Arrays.asList(“Hello”, “Hello”, “World”); Map<String, Long> wordToFrequency = // what goes here? So in this case, I would like the map to consist of these entries: Hello -> 2 … Read more

Java “lambda expressions not supported at this language level”

I was testing out some new features of Java 8 and copied the example into my IDE (Eclipse originally, then IntelliJ) as shown here Eclipse offered no support whatsoever for lambda expressions, and IntelliJ kept reporting an error Lambda expressions not supported at this language level I would like to know if this is a … Read more

What does the arrow operator, ‘->’, do in Java?

While hunting through some code I came across the arrow operator, what exactly does it do? I thought Java did not have an arrow operator. return (Collection<Car>) CollectionUtils.select(listOfCars, (arg0) -> { return Car.SEDAN == ((Car)arg0).getStyle(); }); Details: Java 6, Apache Commons Collection, IntelliJ 12 Update/Answer: It turns out that IntelliJ 12 supports Java 8, which … Read more

How to use a Java8 lambda to sort a stream in reverse order?

I’m using java lambda to sort a list. how can I sort it in a reverse way? I saw this post, but I want to use java 8 lambda. Here is my code (I used * -1) as a hack Arrays.asList(files).stream() .filter(file -> isNameLikeBaseLine(file, baseLineFile.getName())) .sorted(new Comparator<File>() { public int compare(File o1, File o2) { … Read more

WebService Client Generation Error with JDK8

I need to consume a web service in my project. I use NetBeans so I right-clicked on my project and tried to add a new “Web Service Client”. Last time I checked, this was the way to create a web service client. But it resulted in an AssertionError, saying: java.lang.AssertionError: org.xml.sax.SAXParseException; systemId: jar:file:/path/to/glassfish/modules/jaxb-osgi.jar!/com/sun/tools/xjc/reader/xmlschema/bindinfo/binding.xsd; lineNumber: 52; … Read more