I have problem importing java.util.stream.*;
Compiling my code gives me a stream()
"cannot find symbol error".
This is my import list
import java.util.stream.*;
import java.util.*;
import java.lang.String;
import java.util.Arrays;
import java.nio.file.*;
import java.io.IOException;
and this is the code i'm compiling
List<Beverage> l = cantine.stream()
.filter(p -> p.name.equals(nam))
.collect(Collectors.toList());
IMPORTANT: I do know what a "cannot find symbol error" is, so please do not blindly close this question.
full code for reference
import java.util.stream.*;
import java.util.*;
import java.lang.String;
import java.util.Arrays;
import java.nio.file.*;
import java.io.IOException;
public class Enoteca{
Map<String,Beverage> cantine;
public Enoteca(){
this.cantine = new HashMap<String,Beverage>();
}
public List<Beverage> byName(String nam){
List<Beverage> l = cantine.stream()
.filter(p -> p.name.equals(nam))
.collect(Collectors.toList());
}
public static void main(String[] args){
Enoteca e = new Enoteca();
for(String s: args){
Beverage b = new Beverage(s,"1987");
e.cantine.put(s,b);
}
System.out.println(e.cantine);
}
}
class Beverage{
String name;
String year;
public Beverage(String name,String year){
this.name = name;
this.year = year;
}
public String getName(){
return name;
}
#Override
public String toString(){
return name + " " +year;
}
}
The compiler is correct. Map does not have a stream() method. The Collections returned by a Map’s keySet, values, and entrySet methods do, but Map itself does not.
Since you want a List<Beverage>, I’m guessing you want cantine.values().stream().
Related
why can execute my code without any issues and it gives me the correct results.
package com.opennlp.demo;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
public static Set<String> nounPhrases = new HashSet<>();
private static String line = "I need a PHP note if";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP") || p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
//System.out.println(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
System.out.println(child.toString()+"lol");
}
}
public void parserAction() throws Exception {
InputStream is = new FileInputStream("en-parser-chunking.bin");
ParserModel model = new ParserModel(is);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses){
//p.show();
getNounPhrases(p);
}
}
public static void main(String[] args) throws Exception {
new ParserTest().parserAction();
System.out.println("List of Noun Parse : "+nounPhrases);
}
}
below is my second code.. it gives me a blank Array in console.I removed main method from above class and I tried to print the nounPhrases inside another class. it shows a blank array. I think in second code my parserAction method is not executing. How can I do execute that method without a main method in another class ?
my second code
package com.opennlp.demo;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashSet;
import java.util.Set;
import opennlp.tools.cmdline.parser.ParserTool;
import opennlp.tools.parser.Parse;
import opennlp.tools.parser.Parser;
import opennlp.tools.parser.ParserFactory;
import opennlp.tools.parser.ParserModel;
public class ParserTest {
public static Set<String> nounPhrases = new HashSet<>();
//private static String line = "i need a Java book which has JSP also";
private static String line = "I need a PHP note if";
public void getNounPhrases(Parse p) {
if (p.getType().equals("NN") || p.getType().equals("NNS") || p.getType().equals("NNP") || p.getType().equals("NNPS")) {
nounPhrases.add(p.getCoveredText());
//System.out.println(p.getCoveredText());
}
for (Parse child : p.getChildren()) {
getNounPhrases(child);
System.out.println(child.toString()+"lol");
}
}
public void parserAction() throws Exception {
InputStream is = new FileInputStream("en-parser-chunking.bin");
ParserModel model = new ParserModel(is);
Parser parser = ParserFactory.create(model);
Parse topParses[] = ParserTool.parseLine(line, parser, 1);
for (Parse p : topParses){
//p.show();
getNounPhrases(p);
}
}
}
I called the nounPhrases in another class like below. But it shows a blank result. How to fix this ? I need to do this without a main method in this class.
ParserTest pt = new ParserTest();
pt.parserAction();
System.out.println(ParserTest.nounPhrases);
Can someone please help me see what the problem is. I realise that using
String kind = sc.next();
might bring a problem. if that's the issue how do i fix it. Thank you in advance. Here is the code.
import java.io.*;
import java.util.*;
public abstract class Account {
protected static AccountNumber accountNumber;
protected Customer customer = null; // not to be used yet
public abstract MeterNumber[] getMeterNumbers();
public abstract boolean exists(String meterNumber, String tariff);
public static Account load(Scanner sc) {
while (sc.hasNextLine()) {
AccountNumber accountNumber = AccountNumber.fromString(sc.nextLine());
String kind = sc.next();
sc.nextLine();
if (kind.equals("D")) {
return new DomesticAccount(sc, accountNumber);
} else {
return new CommercialAccount(sc, accountNumber);
}
} {
return null;
}
}
}
The code in main is as follows.
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeSet;
public class Testt {
public static void main(String[] args) {
Account.load(new Scanner("Accounts3.txt"));
Map <AccountNumber, String> map1 = new HashMap <AccountNumber, String>();
map1.put(Account.accountNumber, "hello");
System.out.println(map1);
}
}
and this is the error I am getting.
Exception in thread "main" java.util.NoSuchElementException
at java.util.Scanner.throwFor(Scanner.java:862)
at java.util.Scanner.next(Scanner.java:1371)
at Account.load(Account.java:20)
at Testt.main(Testt.java:14)
Your are creating scanner on string object. Which is just "Accounts3.txt". Which is just one line.
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.lang.String)
I think you need to create scanner on file.
Refere this:
http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html#Scanner(java.io.File)
So your main method will create scanner like this:
Account.load(new Scanner(new java.io.File("Accounts3.txt")));
This question already has answers here:
What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?
(18 answers)
Closed 8 years ago.
okay look i know this question has been answered time and time again HOWEVER i seriously can't figure out what im doing wrong.
please help.
i have two classes. Machine.java which is the object class and the InventoryTest.java class that holds the main statement.
everywhere i have read says this should work.
this is in the Machine.java class
public static Comparator<Machine> machineIdNumberComparator = new Comparator<Machine>() {
#Override
public int compare(Machine s1, Machine s2) {
String MachineID1 = s1.getMachineIdNumber();
String MachineID2 = s2.getMachineIdNumber();
//ascending order
return MachineID1.compareTo(MachineID2);
}};
this is in the InventoryTest
Collections.sort(arraylist, inventoryArray.machineIdNumberComparator);
this line comes up with problems. arraylist has cannot find symbol error and so does the machineIdNumberComparator.
i need to be able to sort by 3 different methods.
edit: this is how i add and created my arrayList
public List<Machine> inventoryArray = new ArrayList<>();
inventoryArray.add(new Machine(strMachineIdNumber, strManufacturer, strType, dblPowerOrCapacity, dblPrice));
the arraylist is declaired at the start just under the public class where you declair all your variables.
/**
*
* #author stephankranenfeld
*/
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Collections;
import java.util.Comparator;
import java.util.NoSuchElementException;
import java.util.Scanner;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.JButton;
import javax.swing.JTextArea;
public class InventoryTest extends JFrame {
private static final int FRAME_WIDTH = 800;
private static final int FRAME_HEIGHT = 1500;
private final JTextArea textArea;
private final JButton addMachine;
private final JButton removeMachine;
private final JButton exitButton;
private final JButton sortButton;
final String START_TEXT = String.format("%-20s %-20s %-10s %15s %10s %n", "Machine ID Number:", "Manufacturer:", "Type:", "Power/Capacity:", "Price:"); // starting line of texted used in both display all and entre data buttons.
final String DEVIDER = "-------------------------------------------------------------------------------------\n";// a devider used multple times
public List<Machine> inventoryArray = new ArrayList<>();
/*
junk that isn't needed i think
*/
private void sort() {
JComboBox sortBy = new JComboBox();
sortBy.addItem("ID Number");
sortBy.addItem("Manufacturer");
sortBy.addItem("Type");
int option = JOptionPane.showConfirmDialog(null, sortBy, "Sort by?", JOptionPane.OK_CANCEL_OPTION);
if (option == JOptionPane.OK_OPTION)
{
//if id is selected sort by id
//if manufacturer is selected sor by manufacturer
//if type is selected sort by type
Collections.sort(inventoryArray, Machine.machineIdNumberComparator);
}
}
}
public class Machine{
/*
* all the get and set methods
*/
public static Comparator<Machine> machineIdNumberComparator = new Comparator<Machine>() {
#Override
public int compare(Machine s1, Machine s2) {
String MachineID1 = s1.getMachineIdNumber();
String MachineID2 = s2.getMachineIdNumber();
//ascending order
return MachineID1.compareTo(MachineID2);
}};
The second argument of Collections.sort() should be Machine.machineIdNumberComparator
I connect hadoop with the eclipse ,start the job by eclipse plug-in, the mapreduce job can complete successfully,but when i compile my code to jar file and then execute this job by hadoop command,it will throw errors as follows.
Error:java.lang.IndexOutOfBoundsException:Index:1,Size:1
at java.util.ArrayList.rangecheck(Arraylist.java:635)
at java.util.ArrayList.get(ArrayList.java:411)
at Combiner.reduce(Combiner.java:32)
at Combiner.reduce(Combiner.java:1)
and my code as follows:
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Iterator;
import java.util.PriorityQueue;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapred.MapReduceBase;
import org.apache.hadoop.mapred.OutputCollector;
import org.apache.hadoop.mapred.Reducer;
import org.apache.hadoop.mapred.Reporter;
public class Combiner extends MapReduceBase implements Reducer<Text,Text,Text,Text>{
public void reduce(Text key,Iterator<Text>values,OutputCollector<Text,Text>output,Reporter reporter)
throws IOException{
int num=3;
Comparator<String> comparator=new MyComparator();
PriorityQueue<String> queue=new PriorityQueue<String>(100,comparator);
ArrayList<String> list=new ArrayList<String>();
while(values.hasNext()){
String str=values.next().toString();
queue.add(str);
}
while(!queue.isEmpty()){
list.add(queue.poll());
}
String getCar="";
for(int i=0;i<num;i++){
getCar=getCar+list.get(i)+"\n";
}
output.collect(new Text(""), new Text(getCar));
}
public class MyComparator implements Comparator<String>{
public int compare(String s1,String s2){
if(Long.parseLong(s1.split(",")[4])>Long.parseLong(s2.split(",")[4])){
return 1;
}else if(Long.parseLong(s1.split(",")[4])<Long.parseLong(s2.split(",")[4])){
return -1;
}else{
return 0;
}
}
}
}
This happens, because your list has one element (Size:1), and you ask for the second element (Index:1 - Indexing starts from zero)! A simple System.out.println for each list element will help you get through...
Why do you set the number of elements to 3? If you know that it will be 3 (unlikely), then change the list to an array of size 3. If you don't know that, then change num to list.size(), like:
for(int i=0;i<list.size();i++)
But before anything else, you should understand why you get these values for this key.
I want to use this code and create JSF 2.0 table.
This is the Java Code of the Managed bean:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.inject.Named;
/* include SQL Packages */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
// or import javax.faces.bean.ManagedBean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.glassfish.osgicdi.OSGiService;
#Named("ApplicationController")
#SessionScoped
public class Application implements Serializable {
private List<Item> list;
private transient DataModel<Item> model;
private Item item = new Item();
private boolean edit;
#PostConstruct
public void init() {
// list = dao.list();
// Actually, you should retrieve the list from DAO. This is just for demo.
list = new ArrayList<Item>();
list.add(new Item(1L, "item1"));
list.add(new Item(2L, "item2"));
list.add(new Item(3L, "item3"));
}
public void add() {
// dao.create(item);
// Actually, the DAO should already have set the ID from DB. This is just for demo.
item.setId(list.isEmpty() ? 1 : list.get(list.size() - 1).getId() + 1);
list.add(item);
item = new Item(); // Reset placeholder.
}
public void edit() {
item = model.getRowData();
edit = true;
}
public void save() {
// dao.update(item);
item = new Item(); // Reset placeholder.
edit = false;
}
public void delete() {
// dao.delete(item);
list.remove(model.getRowData());
}
public List<Item> getList() {
return list;
}
public DataModel<Item> getModel() {
if (model == null) {
model = new ListDataModel<Item>(list);
}
return model;
}
public Item getItem() {
return item;
}
public boolean isEdit() {
return edit;
}
}
I get this problem when I import the code into Netbeans:
How I can declare the Java list in order to work?
Best wishes
EDIT I edited the code this way:
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
// or import javax.faces.bean.SessionScoped;
import javax.inject.Named;
/* include SQL Packages */
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import javax.annotation.PostConstruct;
import javax.sql.DataSource;
import javax.annotation.Resource;
import javax.faces.context.FacesContext;
import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
// or import javax.faces.bean.ManagedBean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.glassfish.osgicdi.OSGiService;
#Named("ApplicationController")
#SessionScoped
public class Application implements Serializable {
public Application() {
}
private List<Application> list;
private transient DataModel<Application> model;
private Application item = new Application();
private boolean edit;
private Application(long l, String string) {
throw new UnsupportedOperationException("Not yet implemented");
}
#PostConstruct
public void init() {
// list = dao.list();
// Actually, you should retrieve the list from DAO. This is just for demo.
list = new ArrayList<Application>();
list.add(new Application(1L, "item1"));
list.add(new Application(2L, "item2"));
list.add(new Application(3L, "item3"));
}
public void add() {
// dao.create(item);
// Actually, the DAO should already have set the ID from DB. This is just for demo.
item.setId(list.isEmpty() ? 1 : list.get(list.size() - 1).getId() + 1);
list.add(item);
item = new Application(); // Reset placeholder.
}
public void edit() {
item = model.getRowData();
edit = true;
}
public void save() {
// dao.update(item);
item = new Application(); // Reset placeholder.
edit = false;
}
public void delete() {
// dao.delete(item);
list.remove(model.getRowData());
}
public List<Application> getList() {
return list;
}
public DataModel<Application> getModel() {
if (model == null) {
model = new ListDataModel<Application>(list);
}
return model;
}
public Application getItem() {
return item;
}
public boolean isEdit() {
return edit;
}
private void setId(int i) {
throw new UnsupportedOperationException("Not yet implemented");
}
private int getId() {
throw new UnsupportedOperationException("Not yet implemented");
}
}
Do you see any mistakes?
You have to define the Item class.
UPDATE:
To keep the code in the first form. You should have a Item class.
public class Item {
private long id;
private String name;
public Item() {}
public Item(long id, String name) {
this.id = id;
this.name = name;
}
//getters and setters for the attributes...
}
Now, in your updated code, you're using a list of Application objects. So your Application class should have 2 attributes of long and String type:
//annotations here...
public class Application implements Serializable {
private long id;
private String name;
//getters and setters for these attributes...
public Application() {
//keep your actual code here
}
//we have to add a constructor that receives a long and a String
//to initialize the attributes values.
public Application(long id, String name) {
this.id = id;
this.name = name;
}
//your actual code...
}
Second option is not a good practice, I recommend you separate the Backing Bean (Managed Bean) class from your model classes (in this case, the Item class).
Do not focus on article's code examples only. Read the article's text as well. The text is not written for decoration only :)
The Item class is just a simple model object, its code should be straightforward enough. A Serializable Javabean with two properties Long id and String value, a default constructor and a constructor filling both properties, a bunch of appropriate getters/setters, equals() and hashCode() overriden.
You can almost autogenerate it in its entirety with a bit decent IDE like Eclipse.
From this version of the API, the Item constructor requires a String parameter, which you are not providing. I think your IDE has pulled in that class by accident.
Reading the example from the link in the question I believe you need to supply your own Item class (and import it correctly) which will need a no-argument constructor and one that takes a long and a String.