I'm trying to create a Scrabble game using Java in IntelliJ. I decided to use a Map<Character, Integer> which will contain each letter tile and its corresponding scoring value. I figured I could use the ofEntries shorthand to initialize the values of the Map but each time I try to compile my program I get an error.
error: cannot find symbol Map.entry('A',1)
symbol: method entry(char,int)
location: interface Map
26 errors (1 for each Map entry)
At first I thought it might have something to do with the Map being of type Character, Integer and the error mentioning entry(char,int) but it is my understanding that Java uses autoboxing between primitives and their object wrappers.
import java.util.Map;
class Scrabble {
private final Map<Character, Integer> LETTER_SCORES = Map.ofEntries(
Map.entry('A',1), Map.entry('E',1), Map.entry('I',1), Map.entry('O',1),
Map.entry('U',1), Map.entry('L',1), Map.entry('N',1), Map.entry('R',1),
Map.entry('S',1), Map.entry('T',1), Map.entry('D',2), Map.entry('G',2),
Map.entry('B',3), Map.entry('C',3), Map.entry('M',3), Map.entry('P',3),
Map.entry('F',4), Map.entry('H',4), Map.entry('V',4), Map.entry('W',4),
Map.entry('Y',4), Map.entry('K',5), Map.entry('J',8), Map.entry('X',8),
Map.entry('Q',10), Map.entry('Z',10)
);
private String word;
private int wordScore;
Scrabble(String word) {
this.word = word;
}
Please go to Project Structure | Project | Project SDK and define here JDK > 9 and Language level > 9. Also go to Project Structure | Modules and check that corresponding language level for module is defined here as well. Your code sample should compile without failures with JDK > 9 as was correctly mentioned in comments.
Related
I am currently working on updating drools version from 7.44.0.Final to 7.64.0.Final.
We have some customOperators defined extending BaseEvaluator. I face an issue where a call to fireAllRules() ends up in the following method of EvaluatorWrapper.class file: public void loadHandles(InternalFactHandle[] handles, InternalFactHandle rightHandle) which in turn calls private static InternalFactHandle getFactHandle(Declaration declaration, InternalFactHandle[] handles).
This getFactHandles() throws ArrayIndexOutOfBoundsException. I am expecting 2 entries in handles[] array but it shows just 1 due to which we get the ArrayIndexOutOfBoundsException.
It is suspected that the issue could be due to the following change made in drools version 7.52.0 as detailed out here:
https://docs.jboss.org/drools/release/7.57.0.Final/drools-docs/html_single/index.html#optimize-query-payload
While analyzing further, I updated my drools version to 7.49.0.Final and here it works successfully and the flow does not go to the public void loadHandles(InternalFactHandle[] handles, InternalFactHandle rightHandle) & private static InternalFactHandle getFactHandle(Declaration declaration, InternalFactHandle[] handles) in the EvaluatorWrapper.class file.
Here is the Sample DRL... Problem is with the evaluateRight of the Custom Operation.
import java.util.Date;
...
...
dialect \"mvel\"
rule \"update\"
when
$en : Fact(path == \"Encounter\" )
$a : Fact(path == \"Account\" , (($en.getElement(\"subject\") referenceMatch
this.getElement(\"subject\"))))
then
....
end
Kindly let me know if anyone is aware of or has faced similar issues while updating the drools version.
I understand how to get specific data from a file with Java 8 Streams. For example if we need to get Loaded packages from a file like this
2015-01-06 11:33:03 b.s.d.task [INFO] Emitting: eVentToRequestsBolt __ack_ack
2015-01-06 11:33:03 c.s.p.d.PackagesProvider [INFO] ===---> Loaded package com.foo.bar
2015-01-06 11:33:04 b.s.d.executor [INFO] Processing received message source: eventToManageBolt:2, stream: __ack_ack, id: {}, [-6722594615019711369 -1335723027906100557]
2015-01-06 11:33:04 c.s.p.d.PackagesProvider [INFO] ===---> Loaded package co.il.boo
2015-01-06 11:33:04 c.s.p.d.PackagesProvider [INFO] ===---> Loaded package dot.org.biz
we can do
List<String> packageList = Files.lines(Paths.get(args[1])).filter(line -> line.contains("===---> Loaded package"))
.map(line -> line.split(" "))
.map(arr -> arr[arr.length - 1]).collect(Collectors.toList());
I took (and slightly modified) the code from Parsing File Example.
But what if we also need to get all the dates (and times) for Emitting: events from the same log file? How we can do this within working with the same Stream?
I can only imagine using collect(groupingBy(...)) which groups lines with Loaded packages and lines with Emitting: before parsing and then parse each group (a map entry) separately. But that would create a map with all the raw data from log file which is very memory consuming.
Is there a similar way to effectively extract multiple types of data from Java 8 Streams?
You may solve it without defining new collectors and using third-party libraries in more imperative style. First you need to define a class which represents the parsing result. It should have two methods to accept an input line and combine with existing partial result:
class Data {
List<String> packageDates = new ArrayList<>();
List<String> emittingDates = new ArrayList<>();
// Consume single input line
void accept(String line) {
if(line.contains("===---> Loaded package"))
packageDates.add(line.substring(0, "XXXX-XX-XX".length()));
if(line.contains("Emitting"))
packageDates.add(line.substring(0, "XXXX-XX-XX XX:XX:XX".length()));
}
// Combine two partial results
void combine(Data other) {
packageDates.addAll(other.packageDates);
emittingDates.addAll(other.emittingDates);
}
}
Now you can collect in quite straightforward way:
Data result = Files.lines(Paths.get(args[1]))
.collect(Data::new, Data::accept, Data::combine);
You may use pairing collector which I wrote in this answer and which is available in my StreamEx library. For your concrete problem you will also need a filtering collector which is available in JDK-9 early access builds and also in my StreamEx library. If you don't like using third-party library, you may copy it from this answer.
Also you will need to store everything into some data structure. I declared the Data class for this purpose:
class Data {
List<String> packageDates;
List<String> emittingDates;
public Data(List<String> packageDates, List<String> emittingDates) {
this.packageDates = packageDates;
this.emittingDates = emittingDates;
}
}
Putting everything together you can define a parsingCollector:
Collector<String, ?, List<String>> packageDatesCollector =
filtering(line -> line.contains("===---> Loaded package"),
mapping(line -> line.substring(0, "XXXX-XX-XX".length()), toList()));
Collector<String, ?, List<String>> emittingDatesCollector =
filtering(line -> line.contains("Emitting"),
mapping(line -> line.substring(0, "XXXX-XX-XX XX:XX:XX".length()), toList()));
Collector<String, ?, Data> parsingCollector = pairing(
packageDatesCollector, emittingDatesCollector, Data::new);
And use it like this:
Data data = Files.lines(Paths.get(args[1])).collect(parsingCollector);
I am using Eclipse Juno and Java.
I was trying to create a new list:
List myList = new ArrayList();
This had an error and the resolution on it was along the lines of change compiler to 1.7 which I accepted. The errror on this list creation line was corrected however I now have many errors thoughout the whole project on lines that were previously working. Some examples are:
class GetAccountAndCubsHandler<T> implements AsyncCallback<List<AccountAndCubs>>
Multiple markers at this line
- The hierarchy of the type GetAccountAndCubsHandler is inconsistent
- List cannot he resolved to a type
public class AccountCreationView extends Composite {
Multiple markers at this line
- The hierarchy of the type AccountCreationView is inconsistent
- Breakpoint:AccountCreationView
#SuppressWarnings("unused")
private String accountId;
First line - Multiple markers at this line
- SuppressWarnings cannot be resolved to a type
- The attribute valie is undefined for the annotation type SuppressWarnings
Second line - String cannot be resolved to a type
As you can imagine having my whole project adversely affected in this way is very disconcerting so any advice on how to recover would be greatly appreciated.
Regards,
Glyn
"String cannot be resolved to a type"
Ensure that a valid JRE or JDK is specified in your build-path.
Since you're using Eclipse, right-click on your project, then Properties → Java Build Path.
Perhaps you don't have a Java 7 JRE configured in the Installed JREs preference panel.
I'm new to Scala and our project mixes Java and Scala code together (using the Play Framework). I'm trying to write a Scala method that can take a nested Java Map such as:
LinkedHashMap<String, LinkedHashMap<String, String>> groupingA = new LinkedHashMap<String, LinkedHashMap<String,String>>();
And have that java object passed to a Scala function that can loop through it. I have the following scala object definition to try and support the above Java nested map:
Seq[(String, Seq[(String,String)])]
Both the Java file and the Scala file compile fine individually, but when my java object tries to create a new instance of my scala class and pass in the nested map, I get a compiler error with the following details:
[error] ..... overloaded method value apply with alternatives:
[error] (options: java.util.List[String])scala.collection.mutable.Buffer[(String, String)] <and>
[error] (options: scala.collection.immutable.List[String])List[(String, String)] <and>
[error] (options: java.util.Map[String,String])Seq[(String, String)] <and>
[error] (options: scala.collection.immutable.Map[String,String])Seq[(String, String)] <and>
[error] (options: (String, String)*)Seq[(String, String)]
[error] cannot be applied to (java.util.LinkedHashMap[java.lang.String,java.util.LinkedHashMap[java.lang.String,java.lang.String]])
Any ideas here on how I can pass in a nested Java LinkedHashMap such as above into a Scala file where I can generically iterate over a nested collection? I'm trying to write this generic enough that it would also work for a nested Scala collection in case we ever switch to writing our play framework controllers in Scala instead of Java.
Seq is a base trait defined in the Scala Collections hierarchy. While java and scala offer byte code compatibility, scala defines a number of its own types including its own collection library. The rub here is if you want to write idiomatic scala you need to convert your java data to scala data. The way I see it you have a few options.
You can use Richard's solution and convert the java types to scala types in your scala code. I think this is ugly because it assumes your input will always be coming from java land.
You can write beautiful, perfect scala handler and provide a companion object that offers the ugly java conversion behavior. This disentangles your scala implementation from the java details.
Or you could write an implicit def like the one below genericizing it to your heart's content.
.
import java.util.LinkedHashMap
import scala.collection.JavaConversions.mapAsScalaMap
object App{
implicit def wrapLhm[K,V,G](i:LinkedHashMap[K,LinkedHashMap[G,V]]):LHMWrapper[K,V,G] = new LHMWrapper[K,V,G](i)
def main(args: Array[String]){
println("Hello World!")
val lhm = new LinkedHashMap[String, LinkedHashMap[String,String]]()
val inner = new LinkedHashMap[String,String]()
inner.put("one", "one")
lhm.put("outer",inner);
val s = lhm.getSeq()
println(s.toString())
}
class LHMWrapper[K,V,G](value: LinkedHashMap[K,LinkedHashMap[G,V]]){
def getSeq():Seq[ (K, Seq[(G,V)])] = mapAsScalaMap(value).mapValues(mapAsScalaMap(_).toSeq).toSeq
}
}
Try this:
import scala.collections.JavaConversions.mapAsScalaMap
val lhm: LinkedHashMap[String, LinkedHashMap[String, String]] = getLHM()
val scalaMap = mapAsScalaMap(lhm).mapValues(mapAsScalaMap(_).toSeq).toSeq
I tested this, and got a result of type Seq[String, Seq[(String, String)]]
(The conversions will wrap the original Java object, rather than actually creating a Scala object with a copy of the values. So the conversions to Seq aren't necessary, you could leave it as a Map, the iteration order will be the same).
Let me guess, are you processing query parameters?
I'm writing eclipse plugin that looks for unresolved imports in all source files.
I found that it can be helpful to use IProblem or IMarker objects. Here's code example
public IMarker[] findJavaProblemMarkers(ICompilationUnit cu)
throws CoreException {
IResource javaSourceFile = cu.getUnderlyingResource();
IMarker[] markers =
javaSourceFile.findMarkers(IJavaModelMarker.JAVA_MODEL_PROBLEM_MARKER,
true, IResource.DEPTH_INFINITE);
}
frome here
I don't know how I can get info from IProblem or IMarker about which import cause the compilation problem (unresolved import).
Any help?
http://help.eclipse.org/indigo/index.jsp?topic=/org.eclipse.jdt.doc.isv/guide/jdt_api_classpath.htm
There are a list of different int values in the IProblem interface representing different errors; if you could get the errorcodes of a file somehow, you could use them. (Example, ImportNotVisible, ImportNotFound, etc.). Just check if the error ID matches one of the error ID's for import failures there.
An IMarker knows the line number and start and stop chars for the java source marked by the IMarker. You can take the substring of the java source string and, if the marker type indicates that it's a problem with the class or import, you can search the project's classpath for a class or package matching (or similar to) that substring.