Java sorting with comparator [duplicate] - java

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

Related

Can't import java.util.stream in java 8

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().

Java Eclipse class not found exception (javax/media/opengl/GLCanvas)

I am trying to implement gephi 3d atlas and getting java.lang.NoClassDefFoundError :
Exception in thread "main" java.lang.NoClassDefFoundError: javax/media/opengl/GLCanvas
at org.gephi.visualization.config.VizCommander.createCanvas(VizCommander.java:54)
at org.gephi.visualization.VizController.initInstances(VizController.java:138)
at org.gephi.visualization.VizController.getInstance(VizController.java:94)
at net.clementlevallois.ForceAtlas3D.ForceAtlas2.initAlgo(ForceAtlas2.java:156)
at org.gephi.toolkit.demos.MYSQLImportExport.script(MYSQLImportExport.java:113)
at org.gephi.toolkit.demos.PreviewJFrame.main(PreviewJFrame.java:100)
here is the ForceAtlas2 class implementation (error on last line):
package net.clementlevallois.ForceAtlas3D;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import net.clementlevallois.ForceAtlas3D.ForceFactory.AttractionForce;
import net.clementlevallois.ForceAtlas3D.ForceFactory.RepulsionForce;
import org.gephi.data.attributes.type.TimeInterval;
import org.gephi.dynamic.DynamicUtilities;
import org.gephi.dynamic.api.DynamicController;
import org.gephi.dynamic.api.DynamicModel;
import org.gephi.graph.api.Edge;
import org.gephi.graph.api.GraphModel;
import org.gephi.graph.api.HierarchicalGraph;
import org.gephi.graph.api.Node;
import org.gephi.graph.api.NodeData;
import org.gephi.graph.spi.LayoutData;
import org.gephi.layout.spi.Layout;
import org.gephi.layout.spi.LayoutBuilder;
import org.gephi.layout.spi.LayoutProperty;
import org.gephi.project.api.Workspace;
import org.gephi.visualization.*;
import org.gephi.visualization.api.initializer.Modeler;
import org.gephi.visualization.api.initializer.NodeModeler;
import org.gephi.visualization.api.objects.ModelClass;
import org.gephi.visualization.api.objects.ModelClassLibrary;
import org.openide.util.Exceptions;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import javax.media.opengl.awt.GLCanvas;
import javax.media.opengl.*;
import javax.media.opengl.GL;
import javax.media.opengl.GL2;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCapabilities;
import javax.media.opengl.GLProfile;
import javax.media.opengl.GLEventListener;
import javax.media.opengl.awt.GLCanvas;
import com.jogamp.opengl.*;
import javax.media.opengl.awt.GLCanvas;
/**
* ForceAtlas 2 Layout, manages each step of the computations.
*
* #author Mathieu Jacomy
*/
public class ForceAtlas2 implements Layout {
private GraphModel graphModel;
private HierarchicalGraph graph;
private final ForceAtlas2Builder layoutBuilder;
private DynamicModel dynamicModel;
private double edgeWeightInfluence;
private double jitterTolerance;
private double scalingRatio;
private double gravity;
private double speed;
private boolean outboundAttractionDistribution;
private boolean adjustSizes;
private boolean threeD;
private boolean barnesHutOptimize;
private double barnesHutTheta;
private boolean linLogMode;
private boolean strongGravityMode;
private int threadCount;
private int currentThreadCount;
private Region rootRegion;
double outboundAttCompensation = 1;
//Dynamic Weight
private TimeInterval timeInterval;
private ExecutorService pool;
private ModelClass nodeClass;
private NodeModeler originalNodeModeler;
public ForceAtlas2(ForceAtlas2Builder layoutBuilder) {
this.layoutBuilder = layoutBuilder;
this.threadCount = Math.min(4, Math.max(1, Runtime.getRuntime().availableProcessors() - 1));
}
#Override
public void initAlgo() {
speed = 1.;
graph = graphModel.getHierarchicalGraphVisible();
this.timeInterval = DynamicUtilities.getVisibleInterval(dynamicModel);
graph.readLock();
Node[] nodes = graph.getNodes().toArray();
// Initialise layout data
for (Node n : nodes) {
if (n.getNodeData().getLayoutData() == null || !(n.getNodeData().getLayoutData() instanceof ForceAtlas2LayoutData)) {
ForceAtlas2LayoutData nLayout = new ForceAtlas2LayoutData();
n.getNodeData().setLayoutData((LayoutData) nLayout);
}
NodeData nData = n.getNodeData();
ForceAtlas2LayoutData nLayout = nData.getLayoutData();
nLayout.mass = 1 + graph.getDegree(n);
nLayout.old_dx = 0;
nLayout.old_dy = 0;
nLayout.old_dz = 0;
nLayout.dx = 0;
nLayout.dy = 0;
nLayout.dz = 0;
}
ModelClass nodeClass;
//nodeClass = org.gephi.visualization.VizController.getInstance().getModelClassLibrary().getNodeClass();
//nodeClass = org.gephi.visualization.VizController.getInstance().getModelClassLibrary().getNodeClass();
VizController vc = org.gephi.visualization.VizController.getInstance();
...
Project explorer + jars that I added to the buil dpath attached
any help much appreciated, thanks
Always ensure that you have only the correct version of .jar files in classpath.
Otherwise, Classloader may find the wrong one and try to get the class file, which doesn't actually exist in it, but in the newer jar version. I can definitely tell that this is such a problem. Please try organizing the Classpath only with the required jar files.
Please find out the .jar file which has the same package without GLCanvas class.

mapreduce error:java.lang.indexoutofboundsexception:index:2,size:2

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.

Sort() "cannot find symbol"

Okay i got some issue with the Collection.sort(myintarray); line... it says cannot find symbol trying to make it sort the list so the lowest number in array come first.
package uppgift.pkg1;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Arrays;
/**
* #author Fredrik
*
*/
public class Uppgift1 {
public static void main(String[] args) {
//Anrop av metod
skapaArray();
}
public static void skapaArray() {
List<Integer> myintarray = new ArrayList<Integer>();
int ints = 0;
int size = 1;
while (ints < size) {
myintarray.add(ints);
ints++;
}
Collection.sort(myintarray);
System.out.println(myintarray.size());
}
}
You should use Collections:
java.util.Collections;
and:
Collections.sort(myintarray);
It should be
Collections.sort(myintarray);
Sorting a collection in Java is easy, just use the Collections.sort(Collection) to sort your values.
You can do
Collections.sort(myintarray);
instead of
Collection.sort(myintarray);

Cannot create Java List

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.

Categories

Resources