Menu
  • HOME
  • TAGS

Tomcat failing to startup

java,tomcat,java-8,java-7

This is an error caused by an invalid JVM command-line parameter. Here's one way to reproduce it: C:\>java -agentpath:D:\Program Files\blahblah Error occurred during initialization of VM Could not find agent library D:\Program in absolute path, with error: Can't find dependent libraries Check Tomcat's Java options. Run %CATALINA_HOME%\bin\tomcat8w.exe as administrator, navigate...

First Object in Set> that satisfies a predicate

java,functional-programming,java-8,future,rx-java

I think, your case can be accomplished with a combination of merge, filter and take: List<Observable<HotelInfo>> hotels = new ArrayList<>(); for (URL u : urls) { Observable<HotelInfo> hotelInfo = networkAPI.askHotel(u); hotels.add(hotelInfo); } Observable.merge(hotels) .filter(h -> h.vacancy > 0) .take(1) .subscribe(h -> System.out.println("Winner: " + h), Throwable::printStackTrace); ...

How to get the index and max value of an array in one shot?

java-8,java-stream

Generally, if you need an index, you’ll have to stream over the indices. Then, the task becomes straight-forward: List<Integer> intArr = Arrays.asList(5, 8, 3, 2); IntStream.range(0, intArr.size()) .reduce((a,b)->intArr.get(a)<intArr.get(b)? b: a) .ifPresent(ix->System.out.println("Index "+ix+", value "+intArr.get(ix))); a more elegant solution, which unfortunately incorporates boxing overhead is IntStream.range(0, intArr.size()) .boxed().max(Comparator.comparing(intArr::get)) .ifPresent(ix->System.out.println("Index...

Do repeating annotations need a public container?

java,eclipse,java-8,javac,repeating-annotations

There is no statement regarding accessibility but the specification makes it clear that it is possible that a repeatable annotation may be restricted to be repeatable at certain locations only, due to the way how the containing annotation has been declared. JLS §9.6.3 … T is applicable to at least...

Stuck with java8 lambda expression

java,java-8

You need a second Collector for that mapping : public Map<String,Set<Person>> getPatientsPerSpecialization(){ return this.docLib .values() .stream() .collect(Colectors.groupingBy(Doctor::getSpecialization, Collectors.mapping(Doctor::getPatients,toSet())) ); } EDIT: I think my original answer may be wrong (it's hard to say without being able to test it). Since Doctor::getPatients returns a Collection, I think my code may return...

Consult the code of Java SE 8 online? [closed]

java,java-8

Yes it is possible, you can find it here.

What is the difference between these constructs such that one won't compile?

java,lambda,compilation,java-8

Your initial attempt at wrapConsumer didn't work because it still took a Consumer as a parameter, and your lambda expression that you attempted to wrap still threw an Exception -- a checked exception. Your try/catch is too far from the thrown exception, because at the point you create a lambda...

Gradle Android Project with Java 8 module

java,android,gradle,java-8,android-gradle

Android can support java 1.7 since API 19 (as you see in this doc there is no mention of java 1.8) and also it doesn't use JVM and using ART or Dalvik instead ,So it generates Dalvik bytecode. I think if we want to use java 1.8 as compileOptions maybe...

Apply a list of Functions to a Java stream's .map() method

java,lambda,functional-programming,java-8,java-stream

If lookupFunction(nvp.getName()) returns a Collection of functions, you can get a Stream of that Collection and map each function to the result of applying it to the NameValuePair : List<NameValuePair> newParamPairs = paramPairs.stream() .flatMap((NameValuePair nvp) -> lookupFunction(nvp.getName()).stream().map(func -> func.apply(nvp))) .flatMap(Collection::stream) .collect(toList()); ...

Do the common terminal operations not work with Stream?

java,byte,java-8,java-stream

b >> 1 returns an int which can't be automatically cast to byte. You can just add a cast: .map(b -> (byte) (b >> 1)) ...

Collect results from parallel stream

java,parallel-processing,java-8,java-stream

Your Hen class is poorly adapted to the Stream API. Provided that you cannot change it and it has no other useful methods (like Collection<Egg> getAllEggs() or Iterator<Egg> eggIterator()), you can create an egg stream like this: public static Stream<Egg> eggs(Hen hen) { Iterator<Egg> it = new Iterator<Egg>() { @Override...

Java 8 - Difference between Optional.flatmap and Optional.map

java,java-8

Optional.map() - transform value if present Very often you need to apply some transformation on a value, but only if it’s not null (avoiding NullPointerException): if (x != null) { String t = x.trim(); if (t.length() > 1) { print(t); } } This can be done in much more declarative...

Nested for each loop returning map with Java 8 streams

java,java-8,java-stream

You can often convert your iterative solution directly to a stream by using .collect: Map<Integer, CarShop> result = someListOfCars.stream().collect( HashMap::new, (map, car) -> car.getCarProducts().forEach( prod -> map.put(prod.getId(), car.getCarShop()) ), Map::putAll ); You can make the solution more flexible at the cost of additional allocations: Map<Integer, CarShop> result = someListOfCars.stream() .flatMap(car...

Why is generic of a return type erased when there is an unchecked conversion of a method parameter in Java 8?

java,generics,java-8

This looks like a known compatibility issue reported here and here. From the second link: The following code which compiled, with warnings, in JDK 7 will not compile in JDK 8: import java.util.List; class SampleClass { static class Baz<T> { public static List<Baz<Object>> sampleMethod(Baz<Object> param) { return null; } }...

Java8 LocalDate Time Adding Hours Not Wroking

java-8,java-time

In JDK source code, the instance of LocalDateTime is immutable, /** * Returns a copy of this {@code LocalDateTime} with the specified period in hours added. * <p> * This instance is immutable and unaffected by this method call. * * @param hours the hours to add, may be negative...

Java 8 - return List (keyset) opposed to List>

java,java-8,vaadin

You can add a map call to extract the key from the Entry : List<Integer> keys = checkBoxes.entrySet().stream().filter(c -> c.getValue().getValue()).map(Map.Entry::getKey) .collect(Collectors.toList()); ...

Java label irregularity (possible bug?)

java,label,java-8,standards

The expression int k = 3; is a local variable declaration statement. The statement used in the syntax of a label statement LabeledStatement:   Identifier : Statement does not contain local variable declaration statements. You therefore can't use them within a labeled statement directly. Local variable declaration statements can be used...

How to remove a collect into a new stream from the middle of a java 8 stream?

stream,java-8

No, you have to have some sort of an intermediate data structure to accumulate counts. Depending on how your graph and edge classes are written, you could try to accumulate counts directly into the graph, but that would be less readable and more brittle. Note that you can iterate over...

How to sort HashMap in java depending on the size of value List

java,java-8

Use a TreeMap which is sorted by key so flip the map: import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.TreeMap; public class Test { public static void main(String[] args) { Map<String, List<String>> map = new HashMap<String, List<String>>(); map.put("USA",Arrays.asList(new String[]{"CA","IA","IL"})); map.put("India",Arrays.asList(new String[]{"MUM","CAL"})); map.put("Canada",Arrays.asList(new String[]{"TOR"}));...

Center JoptionPaneMessageDialog in parent element of the source element that generated the event

java,swing,events,java-8

JOptionPane.showMessageDialog(((Component) e.getSource()).getParent(), "pulsado");

Populating a List with a contiguous range of shorts

java,java-8,java-stream

List<Short> range = IntStream.range(0, 500).mapToObj(i -> (short) i).collect(Collectors.toList()); ...

How to use lambda expression to call the comparator?

java,lambda,java-8

In Java, you can’t sort ints as Strings without an explicit conversion, however, it’s still possible to do it in one operation: public String largestNumber(int[] num) { String s=Arrays.stream(num).mapToObj(Integer::toString) .sorted((n1, n2) -> (n2+n1).compareTo(n1+n2)) .collect(Collectors.joining()); return s.charAt(0) == '0'? "0": s; } ...

How to work with Java 8 streams?

java,foreach,java-8,java-stream

No need for a stream here, you can use the new Collection#removeIf method: newStates.removeIf(path::contains); Or, if path is a Collection: newStates.removeAll(path); ...

Lambda Metafactory Variable Capture

java,lambda,java-8

The third argument to the bootstrap method, which you named lambdaType, is the invoked type of the associated invokedynamic instruction (normally filled in by the JVM). It’s semantic is defined by the bootstrap method and in the case of the LambdaMetaFactory, it specifies the functional interface as return type (the...

Parallel stream creates only one thread and gives result as fast as normal stream

multithreading,java-8,java-stream

Looks like currently, Files.lines reads the file linearly, so the parallel call cannot split the source stream into sub-streams for parallel processing. See here for details. Relevant section quoted below: What if my source is based on IO? Currently, JDK IO-based Stream sources (for example BufferedReader.lines()) are mainly geared for...

How To Calculate The Number Of Days In A Period

java,java-8

From the documentation: To define an amount of time with date-based values (years, months, days), use the Period class. The Period class provides various get methods, such as getMonths, getDays, and getYears.To present the amount >of time measured in a single unit of time, such as days, you can use...

Java8 Nested Streams write back with setter

java,java-8,java-stream

I would use a for loop: for (Location location : locations) { List<?> newList = location.getSubList().stream() .filter(this::correctTestDataValue) .collect(Collectors.toList()); location.setSubList(newList); } Or if you can remove in place: for (Location location : locations) { location.getSubList().removeIf(x -> !correctTestDataValue(x)); } Which can work as a stream: locations.stream() .map(Location::getSublist) .forEach(list -> list.removeIf(x -> !correctTestDataValue(x)));...

Java JDK 8 IndexedPropertyDescriptor has changed since JDK 7 with List object

java,java-8,java-7,introspection

Well, the specification clearly says that an IndexedPropertyDescriptor may have additional array based accessor methods, nothing else. That hasn’t changed. What you have here are conflicting property methods defining a simple List<String> typed property and and an indexed String property of the same name. The List based methods were never...

functional way to accumulate pairs in java8

java,functional-programming,java-8,java-stream

You can move the map steps inside the flatMap: return Arrays.stream(names) .<Person>flatMap( name -> getTokensForPerson(name).stream() .filter(Token::isValid) .map(token -> new Person(name, token))) .collect(Collectors.toList()); This way you can access name variable as well. StreamEx-based solution is shorter, though it requires third-party library: return StreamEx.of(names) .cross(name -> getTokensForPerson(name).stream()) // Here we have the...

Implementing swing in jdk 1.8 using eclipse

java,eclipse,swing,java-8

Your project settings are wrong. An ancient question can be found here with the same issue (and the correct way to resolve it). Basically you need to check your project's Build Path to make sure that it's referring to the default JRE and you're not including the Swing classes from...

OrElseGet chaining in Java8

lambda,java-8,optional

The simplest way would be to iterate over the conditions first: Stream.<Predicate<String>>of("AB"::equals, "DC"::equals,"XY"::equals) .flatMap(condition -> test.stream().filter(condition).limit(1)) .findFirst() .orElse(test.get(0)); Of course, since in your sample case all conditions are matches to strings, you could do this simpler, but I assume you mean to ask about a general case. You can also...

How to create a two dimensional array from a stream in Java 8?

java,java-8,java-stream

Given a Stream<String> you can parse each item to an int and wrap it into an Object[] using: strings .filter(s -> s.trim().length() > 0) .map(Integer::parseInt) .map(i -> new Object[]{i}) Now to turn that result into a Object[][] you can simply do: Object[][] result = strings .filter(s -> s.trim().length() > 0)...

Is it possible to truncate date to Month with Java 8?

java,java-8,truncate,java-time

One way would be to manually set the day to the first of the month: import static java.time.ZoneOffset.UTC; import static java.time.temporal.ChronoUnit.DAYS; ZonedDateTime truncatedToMonth = ZonedDateTime.now(UTC).truncatedTo(DAYS).withDayOfMonth(1); System.out.println(truncatedToMonth); //prints 2015-06-01T00:00Z long millis = truncatedToMonth.toInstant().toEpochMilli(); System.out.println(millis); // prints 1433116800000 Or an alternative with a LocalDate, which is maybe cleaner: LocalDate firstOfMonth = LocalDate.now(UTC).withDayOfMonth(1);...

java8 stream grouping and sorting on aggregate sum

java-8,grouping,aggregate,java-stream

Well, you already did the main work by collecting the aggregate information Map<Integer, Integer> totalNoThings = somethings.stream() .collect(Collectors.groupingBy(Something::getParentKey, Collectors.summingInt(Something::getNoThings))); then all you need to do is utilizing these information in a sort operation: List<Something> sorted=somethings.stream().sorted( Comparator.comparing((Something x)->totalNoThings.get(x.getParentKey())) .thenComparing(Something::getNoThings).reversed()) .collect(Collectors.toList()); ...

Double a stream

java,java-8,java-stream

Create an inner stream which will contain current element two times and flatMap this stream. stream.flatMap(e -> Stream.of(e,e)) If you want to multiply the number of elements by n you can create a utility method like this one: public static <T> Stream<T> multiplyElements(Stream<T> in, int n) { return in.flatMap(e ->...

How to check if Collection is not empty using java Stream

java,lambda,stream,java-8

You are mixing two things up. The first task is to convert the Iterable to a Collection which you can indeed solve using the Stream API: Collection<User> list= StreamSupport.stream(userRepository.findAll(pks).spliterator(), false) .collect(Collectors.toList()); Note that this stream is a stream of Users, not a stream of lists. Therefore you can’t map a...

How i can get list from some class properties with java 8 stream

java,collections,java-8,java-stream

That's basic, you use map : List<String> names = personList.stream() .map(Person::getName) .collect(Collectors.toList()); EDIT : In order to combine the Lists of friend names, you need to use flatMap : List<String> friendNames = personList.stream() .flatMap(e->e.getFriends().stream()) .collect(Collectors.toList()); ...

Java 8 : Lambda Function and Generic Wildcards

java,lambda,java-8

The Function<? extends Borrowable, String> type means function that able to accept some type which extends Borrowable. It does not mean that it accepts Book. Probably the best solution is to introduce the generic parameter for Borrowable: public interface Borrowable<T> { public String toString(Function<? super T, String> format); } And...

State in a java.util.function.Function

lambda,java-8,java-stream

There is nothing wrong with your approach. I feel that this will simplify my implementation but worry that this goes against the whole functional programming paradigm. To solve this, you could implement a method, which gets your start and end date, and returns you a function. For example: public static...

How to convert single element list to java 8 optional

java,collections,java-8,optional

You can use the Stream#findFirst() method, which: Returns an Optional describing the first element of this stream, or an empty Optional if the stream is empty. List<Integer> list = ... Optional<Integer> optional = list.stream().findFirst(); Alternatively, with the same success you can also use the Stream#findAny() method....

Passing method as a parameter - Is this possible?

java,java-8

Since you want to express code which works on a Session instance (so you can abstract the creation and cleanup of it) and might return an arbitrary result, a Function<Session,T> would be the right type for encapsulating such code: public <T> T doWithSession(Function<Session,T> f) { Session session = sessionFactory.openSession(); try...

Take out the hour, min and second in new Date/Time in Java 8

java,java-8,localtime

If you use the base time points, LocalTime.of(05, 00) and LocalTime.of(17, 00) you are using times of today. If I understand you correctly, you want calculate duration relative to the closest points which implies that if evening has passed, you would calculate the time relative to tomorrow’s morning or relative...

operators in predicate as argument in lambda expression

java,lambda,type-conversion,java-8,predicate

What is happening is that you're using a raw java.util.function.Predicate, on which the test() method would look like: public void test(Object o) { ... } This is why you get a compile-time error: the argument type is Object and the numeric operators (<, >) are not applicable for the type...

Collect list of Long from Double stream in Java 8

java,java-8,java-stream

This should compile if you use map instead of mapToLong. (I'm not sure what you are trying to do with doubleToRawLongBits makes any sense, but that will at least compile.)

Spring Integration Java DSL - @ServiceActivator method with @Header parameter annotations

java-8,spring-integration

Not exactly, you can't pass the whole message and selected headers, but you can pass the payload and individual headers... .handle(String.class, (p, h) -> aService().serviceMethod(p, (AState) h.get(ServiceHeader.A_STATE), (String) h.get(ServiceHeader.A_ID))) (assuming the payload is a String). Note that the @Header annotations are meaningless in this scenario because you are directly pulling...

Java byte array doesn't convert back to its original string when using DatatypeConverter

java,arrays,byte,java-8

The strings don't match because they shouldn't. The operation printBase64Binary turns an arbitrary byte stream into a sequence of printable ASCII characters. However, this sequence won't just contain any old collection of printable ASCII characters - if a string is a valid Base64 translation of some byte sequence then there...

Split and Loop in java 8

java,split,java-8

Here's Java-8 solution: static void getResponse(String input, int level) { Stream.iterate(input, str -> { int pos = str.lastIndexOf('.'); return pos == -1 ? "" : str.substring(0, pos); }).limit(level+1).forEach(System.out::println); } If you know for sure that level does not exceed the number of dots, you can omit the check: static void...

Java 8 Stream with batch processing

java,stream,java-8,batch-processing

You could do it with jOOλ, a library that extends Java 8 streams for single-threaded, sequential stream use-cases: Seq.seq(lazyFileStream) // Seq<String> .zipWithIndex() // Seq<Tuple2<String, Long>> .groupBy(tuple -> tuple.v2 / 500) // Map<Long, List<String>> .forEach((index, batch) -> { process(batch); }); Behind the scenes, zipWithIndex() is just: static <T> Seq<Tuple2<T, Long>> zipWithIndex(Stream<T>...

estimateSize() on sequential Spliterator

java,java-8,java-stream,spliterator

Looking at the call hierarchy to the relevant spliterator characteristic reveals that it's at least relevant for stream.toArray() performance Additionally there is an equivalent flag in the internal stream implementation that seems to be used for sorting: So aside from parallel stream operations the size estimate seems to be used...

Java 8 , JCE Unlimited Strength Policy and SSL Handshake over TLS

java,ssl,jvm,centos,java-8

Try limiting the protocols to just TLSv1 using: -Djdk.tls.client.protocols=TLSv1 See this page for more details: https://docs.oracle.com/javase/8/docs/technotes/guides/security/jsse/JSSERefGuide.html#descPhase2 Hope this helps, Yuri...

Java 8 lambdas nested Map

java,lambda,java-8,java-stream,collectors

Your class design seems odd to me. Why put category into the summary class only to then have the category as a map key? It would make more sense to have a summary class without category in it: public class TransactionSummary { private final BigDecimal amount; private final Map<String, BigDecimal>...

Merging two List of objects in java 8

java,stream,java-8

If you want to implement equals and hashCode, the place to do it is inside the class Parent. Within that class add the methods like @Override public int hashCode() { return Objects.hash(getAttrib1(), getAttrib2(), getAttrib3(), // … getAttrib19(), getAttrib20()); } @Override public boolean equals(Object obj) { if(this==obj) return true; if(!(obj instanceof...

Cannot load font in JRE 8

java,fonts,awt,java-8

It turns out that this is a problem with the openjdk-8-jre-headless installation. This is the installation in the Docker image for java 8 JRE. I simply install openjdk-8-jre (without headless) and the problem goes away. If you look at the error log, the loading of the font require awt X11,...

Java 8 - Call interface's default method with double colon syntax

java,inheritance,lambda,java-8

One way would be to put the compare method in a static method: public static interface IdEntity extends Comparable<IdEntity> { int getId(); @Override default int compareTo(IdEntity other) { return defaultCompare(this, other); } static int defaultCompare(IdEntity first, IdEntity second) { return first.getId() - second.getId(); } } Then your method would be:...

Why are Java 8's functional-style constructs called “streams”?

java,java-8,java-stream

A "stream" is not necessarily related to I/O but is a generalized concept referring to information flowing through a system. The notion of Stream Processing (Wikipedia link by Mr.Me) having to do with SIMD processing or vector-based computing is also similar to the computational style afforded by the Java 8...

How to use Java 8 Collectors groupingBy to get a Map with a Map of the collection?

java-8,java-stream,collectors

groupingBy accepts a downstream collector, which can also be a groupingBy: subjects.stream() .collect(groupingBy( Subject::getOrigin, groupingBy(Subject::getType) )); ...

How to parse non-standard month names with DateTimeFormatter

java,datetime,localization,java-8,java-time

The answer to the problem is the DateTimeFormatterBuilder class and the appendText(TemporalField, Map) method. It allows any text to be associated with a value when formatting or parsing, which solves the problem effectively and elegantly: Map<Long, String> monthNameMap = new HashMap<>(); map.put(1L, "Jan."); map.put(2L, "Feb."); map.put(3L, "Mar."); DateTimeFormatter fmt =...

Mapping a list to Map Java 8 stream and groupingBy

java,collections,lambda,java-8

You could do it like this: Map<String, List<String>> library = books.stream() .flatMap(b -> b.getAttribute().entrySet().stream()) .collect(groupingBy(Map.Entry::getKey, mapping(Map.Entry::getValue, toList()))); From the Stream<Book>, you flat map it with the stream of each map it contains so that you have a Stream<Entry<String, String>>. From there you group the elements by the entries' key and...

Not getting correct timezone in Java 8?

java,java-8,java-time

A LocalDateTime is a date and time without a timezone. When you create a ZonedDateTime object out of it, you're explicitly attaching a timezone to the LocalDateTime. It's not going to convert from your timezone to the Europe/Paris timezone; note that the LocalDateTime does not have a timezone at all;...

JavaFX Tableview not populating data to column

javafx,java-8,javafx-8

You have a copy-paste typo in TableColumn<Counters, String> val4 = new TableColumn<Counters, String>("Value4"); val3.setCellValueFactory(new PropertyValueFactory<Counters, String>("val4")); Should be TableColumn<Counters, String> val4 = new TableColumn<Counters, String>("Value4"); val4.setCellValueFactory(new PropertyValueFactory<Counters, String>("val4")); and val4 is always val4 = "" thats why it looks like they both are empty...

Generic method to perform a map-reduce operation. (Java-8)

java,function,generics,java-8,overloading

The example you present in your question has got nothing to do with Java 8 and everything to do with how generics work in Java. Function<T, Integer> function and Function<T, Double> function will go through type-erasure when compiled and will be transformed to Function. The rule of thumb for method...

Java8 LocalDateTime to XMLGregorianCalender Remove “+05:30” Portion

java-8,java-time

Use this code: LocalDateTime currentUTCTime = LocalDateTime.now(); // using system timezone XMLGregorianCalendar xml = DatatypeFactory.newInstance().newXMLGregorianCalendar(currentUTCTime.toString()‌​); Explanation: The code makes use of the given factory method expecting a lexicographical representation of a local timestamp in ISO-8601-format. And since a LocalDateTime does not refer to any timezone, its output via toString() cannot...

Java 8 Optional.ifPresent is my code wrong or is it eclipse?

eclipse,java-8,nullable,optional

JDT's null analysis cannot know about the semantics of each and every method in JRE and other libraries. Therefore, no conclusions are drawn from seeing a call to ifPresent. This can be remedied by adding external annotations to Optional so that the analysis will see method ofNullable as <T> Optional<@NonNull...

JavaFx: Button border and hover

java,css,javafx,java-8

Use the styles to remove the background : .button { -fx-background-color: transparent; } On hover, to bring back everything just use the button style from modena.css : .button:hover{ -fx-background-color: -fx-shadow-highlight-color, -fx-outer-border, -fx-inner-border, -fx-body-color; -fx-background-insets: 0 0 -1 0, 0, 1, 2; -fx-background-radius: 3px, 3px, 2px, 1px; -fx-padding: 0.333333em 0.666667em 0.333333em...

Java constructor reference assignment Vs new created object assignment

java,constructor,java-8,variable-assignment,method-reference

MyInterface var = new MyClass(); creates an instance of MyClass and assigns it to a variable of type MyInterface. This requires that MyClass implements MyInterface and have a no-arg constructor. The result is an instance of MyClass which implements MyInterface however it likes to. MyInterface var = MyClass::new; attemps to...

Spring Integration - @Filter discardChannel and/or throwExceptionOnRejection being ignored?

java-8,spring-integration

The annotation configuration is for when using annotation-based configuration. When using the dsl, the annotation is not relevant; you need to configure the .filter within the DSL itself... .filter("@messageFilter.filter('payload')", e -> e.discardChannel(discardCh()) ...

Why I'm getting different java versions

java,terminal,java-8

Could it be that you installed the JRE 8 update 45 but still have version 8 update 31 for JDK?

Functional Interface Inheritance Quirk

java,lambda,java-8,default-method,functional-interface

As stated in the comments, it compiles fine with the oracle compiler. It is an eclipse bug. Awaiting for a bug fix, personally i will remove the annotation @FunctionalInterface (your 3rd variation): public interface Function<T, R> extends java.util.function.Function<T, R>, com.google.common.base.Function<T, R> { R call(T input); @Override default R apply(T input)...

RoundingMode.HALF_DOWN issue in Java8

java,java-8,rounding,number-rounding

Seems that it's intended change. The JDK 1.7 behavior was incorrect. The problem is that you simply cannot represent the number 10.55555 using the double type. It stores the data in IEEE binary format, so when you assign the decimal 10.55555 number to the double variable, you actually get the...

How to wrap a method that returns an optional with fromNullable?

java-8,guava,optional

Use Optional<Boolean> x = get_I_dontHaveControlOverThisMethod(); if(x == null) x = Optional.absent(); If you are calling such methods quite often, you can wrap it into function: static <T> Optional<T> safeOptional(Optional<T> optional) { return optional == null ? Optional.absent() : optional; } And use: Optional<Boolean> x = safeOptional(get_I_dontHaveControlOverThisMethod()); ...

Why does parallelStream not use the entire available parallelism?

java,multithreading,java-8,java-stream,fork-join

Why are you doing this with ForkJoinPool? It's meant for CPU-bound tasks with subtasks that are too fast to warrant individual scheduling. Your workload is IO-bound and with 200ms latency the individual scheduling overhead is negligible. Use an Executor: import static java.util.stream.Collectors.toList; import static java.util.concurrent.CompletableFuture.supplyAsync; ExecutorService threads = Executors.newFixedThreadPool(25); List<MyObject>...

Java 8, using .parallel in a stream causes OOM error

java,parallel-processing,java-8,java-stream

Here you create an infinite stream and limit it afterwards. There are known problems about processing infinite streams in parallel. In particular there's no way to split the task to equal parts effectively. Internally some heuristics are used which are not well suitable for every task. In your case it's...

Maven error with Java 8

java,maven,java-8

Add plugin configuration for the compiler: <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <verbose>true</verbose> <fork>true</fork> <source>1.8</source> <target>1.8</target> </configuration> </plugin> ...

Is it possible to pass argument via method reference?

java,java-8,argument-passing,method-reference

It's not possible to "bind" and argument directly to the method reference. In this case you can easily use lambda: this.job = () -> myImporter.importProducts(myNewArgument); Alternatively if it fits your situation consider leaving the zero-arguments importProducts method which just calls the one-argument importProducts with proper argument value: public void importProducts()...

How can I suppress anonymous new runnable() can be replaced with lambda

java,android,lambda,java-8

After searching with Google, I have realized that Android does not support JDK8 yet officially. See this link Though we can JDK8 flavored coding using Retrolambda, (For Android Studio, it is gradle-retrolambda), or RxJava, they are just a FLAVOR ... My problem was caused by installing JDK8, instead of should...

Trying to use lambda for the first time and the code doesn't compile [closed]

eclipse,lambda,java-8

You need to download the latest version of eclipse from here:https://eclipse.org/downloads/ Take the Luna version. ...

Java 8 parallelStream for concurrent Database / REST call

java,multithreading,concurrency,parallel-processing,java-8

You can do the operation with map instead of forEach - that will guarantee thread safety (and is cleaner from a functional programming perspective): List<String> allResult = partitions.parallelStream() .map(this::callRestAPI) .flatMap(List::stream) //flattens the lists .collect(toList()); And your callRestAPI method: private void callRestAPI(List<String> serverList) { List<String> result = //Do a REST call....

How should I be using LambdaMetaFactory in my use case?

java,reflection,lambda,java-8

If you looked at your log output you noticed that your target method signature looks like (Lme/b3nw/dev/Events/Vanilla;Lme/b3nw/dev/Events/GameEvent;)Z, in other words, since your target method is an instance method, it needs an instance of its class (i.e. Vanilla) as first argument. If you don’t provide an instance at lambda creation time...

java 8 stream groupingBy sum of composite variable

java,sorting,java-8,grouping,java-stream

Unless I'm mistaken, you can not do both sorts in one go. But since they are independent of each other (the sum of the nothings in the Anythings in a Something is independent of their order), this does not matter much. Just sort one after the other. To sort the...

Java 8 stream group by min and max

java,java-8,java-stream

class Pair<T, U> { public final T x; public final U y; public Pair(T x, U y) { this.x = x; this.y = y; } } Collector<Aggregate, ?, Pair<Integer, Integer>> aggregateSalary = mapping(a -> new Pair<>(a.getMinSalary(), a.getMaxSalary()), reducing(new Pair<>(Integer.MAX_VALUE, Integer.MIN_VALUE), (a, b) -> new Pair<>(Math.min(a.x, b.x), Math.max(a.y, b.y)))); Map<String,...

java8 stream grouping aggregate

sum,java-8,grouping,java-stream

First I assume that you are using java.util.Date (though I'd advise you to move to new java.time API). Second, I assume that Something class has also properly implemented equals and hashCode. Also more getters are necessary: String getParentName() { return parentName; } Date getAt() { return at; } Under these...

Eclipse Kepler is unable to set the Java jdk 1.8 when maven project is updated

java,maven,java-8,eclipse-kepler

With the help of Hogler's comment above I am able to reswolve this issue Just did this : https://wiki.eclipse.org/JDT/Eclipse_Java_8_Support_For_Kepler...

How can I find the largest M numbers from N numbers in Java 8?

java,algorithm,java-8,java-stream

If you must use Streams: IntStream.of(arr).sorted().skip(N-M) Otherwise use a PriorityQueue and write yourself an inverting Comparator. Insertion will be O(N(log(N)) and removal of M elements will be O(M(log(N)). Not what you asked for, but maybe close enough....

How to stop a reduce operation mid way based on some condition?

java-8,java-stream

Reduction is meant to work on an entire set of values without specifying in which order the actual processing is going to happen. In this regard, there is no “stopping at point x” possible as that would imply an order of processing. So the simple answer is, reduce does not...

What does :: operator Java means? [duplicate]

java-8

These are method references. It's just a simpler way to write a lambda expression: .map(Tests::doubleIt) is equivalent to .map(i -> Tests.doubleIt(i)) You can also refer to instance methods using someObject::someMethod, or even to constructors using SomeClass::new....

Play! Framework support for Java 8 Optional

java,playframework,playframework-2.0,java-8

It is not possible right now. There is an github issue to replace F.Option with java.util.Optional. It will be delivered in Playframework 2.5.0.

Builder pattern with a Java 8 Stream

java,java-8,builder,java-stream

There's unfortunately no foldLeft method in the stream API. The reason for this is explained by Stuart Marks in this answer: [...] Finally, Java doesn't provide foldLeft and foldRight operations because they imply a particular ordering of operations that is inherently sequential. This clashes with the design principle stated above...

Ensure List of elements ordered by field in element

collections,java-8,guava,method-reference

assertThat("Ordered by age", Ordering.from(Comparator.comparing(Employee::getAge)).isOrdered(list); or assertThat("Ordered by age", Ordering.natural().onResultOf(Employee::getAge).isOrdered(list); ...

C# + linq(concat) rewrite to java

java,c#,linq,java-8

var q = (from edge in this.Edges where edge.Start == v select edge.End) .Concat(from edge in this.Edges where edge.End == v select edge.Start); this is same as var q = ctx.Edges.Where(o => o.Start == v).Select(o => o.End).Union( ctx.Edges.Where(o => o.End == v).Select(o => o.Start)).ToList(); and this would be Stream<Node> q...

Convert time based on timezone using java.time

java,time,java-8,java-time

This answer might be somehow more structured than the correct answer of Jon Skeet. In my comment above I have also pointed out not to overlook the immutable nature of DateTimeFormatter so please always assign the result of any method prefixed by "with...()" to a variable of same type. //...

java 8 - some error with compiling lambda function

java-8

Run javac -version and verify that you are actually using the compiler from JDK8, it's possible that even if your java points to the 1.8 releaase, your javac has a different version. If you are using Eclipse, remember to set the source type for your project to 1.8. Edit: Since...