Im using arraydeque to create list of items and pass them parameters(Items is class)
ArrayDeque<Item> Items= new ArrayDeque<Item>();
But I have problem with java ArrayDeque. Maybe there are ways to add more than one element at once.
For example. I want add at the same time TableType and colourOfTable into ArrayDeque.
In c++ I could have done it with this
vector<Item>Items
Items.push_back(Item("CoffeeTable", "brown"));
I want to do the same thing with Java. Instead of creating a new obj for every item, as:
ArrayDeque<Item> Items = new ArrayDeque<Item>();
Item obj = new Item("CoffeTable", "brown");
Items.add(obj);
Item obj1 = new Item("DinnerTable", "Black");
Items.add(obj1);
But instead of obj I want to add "CoffeTable", "brown" at the same time and with one code line (like in c++ example) into the Items array.
I tried something like that
ArrayDeque<Item> Items= new ArrayDeque<Item>();
Items.add(Items("CoffeTable", "brown"));
But then got the error while creating create method 'Items(String,String)'
You can simple create the new item in the call of add:
items.add(new Item("CoffeTable", "brown"));
So you don't need an explicit variable.
Also note that in Java variable names normally start with a lower case character.
You will have to create a new object anyway to hold these 2 values.
You can do this:
Items.add(new Item("CoffeTable", "brown"));
Anything else you come up with will be syntactic sugar for the above
For example: you can add a static method to your class:
public static Item item(String k1, String k2) {
return new Item(k1, k2);
}
And use it later:
Items.add(item("CoffeTable", "Brown"));
Here is a solution which would surely work. You can add a function to your class itemAdd() as follows:
class Samp {
public static void main(String args[]){
//code.....
ArrayDeque<Item> Items= new ArrayDeque<Item>();
Items.add(itemAdd("CoffeeTable", "brown"));
//rest of code....
}
public static Item itemAdd(String tableType,String colourOfTable){
return new Item(tableType,colourOfTable);
}
}
class Item{
String tableType;
String colourOfTable;
Item(String tableType,String colourOfTable ){
this.tableType=tableType;
this.colourOfTable=colourOfTable;
}
}
Its similar to what u need to do!! Best of luck :)
Related
I've been stuck on this question in an assignment in which I must "List the stations along a given subway line"
There are two Hash Maps:
private Map<String, Station> allStations = new HashMap<String, Station>(); // all stations, indexed by station name
private Map<String, SubwayLine> allSubwayLines = new HashMap<String, SubwayLine>(); // all subway lines, indexed by name of the line
I am trying to call the "getStations()" method, which is a part of the subwayLine class:
public List<Station> getStations(){
return Collections.unmodifiableList(stations);
}
On a subwayLine object which is linked to a button:
public void listStationsOnLine(){
UI.clearText();
List<SubwayLine> subwayLines = new ArrayList(allSubwayLines.values());
for(SubwayLine s : subwayLines){
s.getStations();
}
}
However, this does nothing. Is there anyway in which I can return the stations along the given subwayLine?
you have to save your data in an arraylist again :
public void listStationsOnLine(){
UI.clearText();
List<SubwayLine> subwayLines = new ArrayList(allSubwayLines.values());
List<Collection<Station>> stations = new ArrayList();
for(SubwayLine s : subwayLines){
stations.add(s.getStations());
}
}
The void keyword in your method means that it does not return anything.
You might want to replace it with List and return it at the end of your method, like
public List<Station> listStationsOnLine(){
UI.clearText();
List<SubwayLine> subwayLines = new ArrayList(allSubwayLines.values());
List<Collection<Station>> stations = new ArrayList<>();
for(SubwayLine s : subwayLines){
stations.add(s.getStations());
}
return stations
}
Please note that you loop through all subwaylines and therefore your stations arraylist consists of all stations that are along some subwayline. So not a list of stations per subwayline. Also, I added a diamond operator to the arraylist call. That will automatically make an ArrayList of the type Collection<Station>. However, making a List of Collections seems not right here? You probably just want a List of <Station>.
Moreover, the call s.getStations() seems to yield all stations at subwayLine s? The description of your question seems to ask how to implement thát method.
In your question, you seem to prefer a list of stations for a given subwayline. That should then be input for your method, something like this:
public List<Station> listStationsOnLine(SubwayLine subwayline){
UI.clearText();
List<Station> allStations = getStations();
List<Station> stations = new ArrayList<>();
for(Station s : allStations){
if(s.onLine(subwayline)) {
stations.add(s);
}
}
return stations
}
I know how to put class objects to an ArrayList in java (since new objects can be appended without knowledge of an index first) but I was wondering if there is a simpler way of adding them to an ArrayList and iterating over them?
I was even thinking that, hypothetically, if I kept my object names in a pattern, that I should be able to add each object to the list using a loop e.g. car1, car2, car3, ...
import java.util.ArrayList;
public class TestCar {
public static void main(String[] args) {
ArrayList<String> carNames = new ArrayList<>();
// Cars have simple getter methods corresponding with String and int
Car car1 = new Car("Rav4", 2017);
carNames.add(car1.getName());
Car car2 = new Car("Commodore", 2005);
carNames.add(car2.getName());
for (int i = 0; i < carNames.size(); i++) {
System.out.println(carNames.get(i));
}
}
}
As always, thanks for any replies!
Assuming you are using Java 8 or higher, you could add your Car objects to a list and use streams to get a list of carNames :
List<Car> myCarList = Arrays.asList( new Car("Rav4", 2017), new Car("Commodore", 2005));
List<String> carNames = myCarList.stream()
.map(Car::getName)
.collect(Collectors.toList());
I have a huge group of keys like more than 10L like the below in csv file
ABA,100
ABC,200
ABCs,50
ABM,65
ABMs,86
ABS,86
AC,54
ACLU,123
ACT,56
ACTH,154
AD,644
ADC,76
ADD,10.
Do I need to create the user define an object for the above key pairs? Will it create any memoery problem for creating more than 10L user define object?
My input String looks like [ABS,AC,ACLU,ABC]
I want the output AC,ABS,ACLU,ABC based on the count.
How to achieve it in easier way of Java 1.8.
Thanks.
You could add each line of your csv to a List<String> myList
Then, you will have to create a custom Comparator in order to sort your list based on the value, so something like the following,
private void customSorting(List<String> myList) {
Collections.sort(myList, (String s1, String s2) -> {
String valuePart1 = s1.split(",")[1];
String valuePart2 = s2.split(",")[1];
return Integer.valueOf(valuePart1).compareTo(Integer.valueOf(valuePart2));
});
}
Finally, just call your method like customSorting(myList); in any place of your code you need it
Of course, you have to modify the sorted list as well to keep only the first part (before comma) for each String value but that's easy.
An alternative could also be to create a class like the following,
public class MyClass {
private String key;
private String value;
// All the getters, setters, constructors, etc
}
, and then read each line of your csv, create an equivalent MyClass POJO and add it to a List<MyClass> myList.
You have to write your own custom Comparator again for List<MyClass> in a similar way like I did for the List<String>,
private void customSorting(List<MyClass> myList) {
Collections.sort(myList, (MyClass a, MyClass b) -> {
return Integer.valueOf(a.getValue()).compareTo(Integer.valueOf(b.getValue()));
});
}
Finally, create a new list from the sorted one by keeping only the keys
I have two different methods which fetch data from tow different DB tables. I will add both data into same ArrayList using bean class.
List<LeadVO> leadvoList = new ArrayList<LeadVO>(); // array list declaration
In the while loop I will load all the data using bean class. Before this action I will fire query for both tables.
while(true){
LeadVO statusVO = new LeadVO(); //initializing bean class
// code to load all value using setters
Finally I will add this bean to array list:
leadvoList.add(statusVO);
created seperate class to compare
public class ComparatorDAO implements Comparator {
public int compare(LeadVO arg0, LeadVO arg1) {
return arg1.getCreatedtimeFormat().compareTo(arg0.getCreatedtimeFormat()) ;
}
}
Collections.sort(commentVOList,new ComparatorDAO()); //sorting method
ideally this will not sort according to date i believe this will treat date as string
please help me in this
thanks once again
Now I need to sort this list in date order which is already present in the list. I mean the date which is present in the list.
If your LeadVO contains the date you want to sort by, implement Comparable interface in your VO and then sort the VO collection using Collections.sort().
public class LeadVO implements Comparable<LeadVO> {
private Date date;
// other properties, getters and setters
#Override
public int compareTo(LeadVO other) {
return date.compareTo(other.getDate());
}
}
and the sort like this:
Collections.sort(leadVoList);
You should ideally add null checks or use something like ObjectUtils.compare from commons-lang if your date is not guaranteed to be non-null.
Also you could do this by creating a Comparator instead of implementing Comparable as suggested by other posters, which might be better if you need to sort your VO by multiple values. If you just need to sort it by date, this approach might be a little simpler.
Here is the Example:Hope you don't mind hard interpretation.
List<String> unsortList = new ArrayList<String>();
unsortList.add("CCC");
unsortList.add("111");
unsortList.add("AAA");
unsortList.add("BBB");
unsortList.add("ccc");
unsortList.add("bbb");
unsortList.add("aaa");
unsortList.add("333");
unsortList.add("222");
//before sort
System.out.println("ArrayList is unsort");
for(String temp: unsortList){
System.out.println(temp);
}
//sort the list
Collections.sort(unsortList);
//after sorted
System.out.println("ArrayList is sorted");
for(String temp: unsortList){
System.out.println(temp);
}
}
You can sort arrayList using a comparator:
public Comparator<Record> RecordComparator = new Comparator<Record>() {
public int compare(Record record1, Record record2) {
return record1.getDate().compareTo(record2.getDate());
}
};
and then:
Collections.sort(list, new RecordComparator());
U'll need to override that class compareTo method as it is the method which java looks at for sorting
Simply override the fields that u need sorted
compareTo(Object other){Someclass.somefield.compareTo(other.smeField)}
I need to create a Hallway class which will have inside 2 ArrayLists of Stand objects , one for the stands on the right, and the other for the ones on the left.
My intention is to put these ArrayLists inside another collection in this class.
I don't know if I should use a Hashtable, a Map, etc.
More importantly, my intention is to then access these ArrayLists using a method like:
TheHashTable["Right"].add(standObject); // Add a Stand to the Right Stands ArrayList which is inside a Hashtable.
Example:
public class Hallway {
private Hashtable< String, ArrayList<<Stand> > stands;
Hallway(){
// Create 2 ArrayList<Stand>)
this.stands.put("Right", RightStands);
this.stands.put("Left", LeftStands);
}
public void addStand(Stand s){
this.stands["Right"].add(s);
}
}
Would this be possible?
It is possible, but I would advise against it. If you have only two stand locations, it would be much and clearer to simply have two variables of type List<Stand>: leftStands and rightStands, and to have corresponding methods: addLeftStand(Stand), addRightStand(Stand), etc. The code would be much clearer, simpler and safer.
If you really want to go your way, the keys of the map shouldn't be Strings. The caller wouldn't know which key to pass to your methods (there are an infinity of Strings), and ven if he knows that the keys are "Right" and "Left", he could make a typo which would go unnoticed by the compiler. You should use an enum instead, which would make the code self-documented and safer:
public enum Location {
LEFT, RIGHT
}
private Map<Location, List<Stand>> stands = new HashMap<Location, List<Stand>>();
public Hallway() {
for (Location location : Location.values()) {
stands.put(location, new ArrayList<Stand>());
}
}
public void addStand(Location location, Stand stand) {
stands.get(location).add(stand);
}
if you only have right and left, you could for example just create 2 array lists.
private ArrayList<Stand> rightStands;
private ArrayList<Stand> leftStands;
If I understood your question clearly, then this is what you want:
public void addStand(Stand s){
this.stand.get("Right").add(s);
}
But a better approach would be to use Map instead of Hashtable.
public class Hallway {
private Map< String, ArrayList<<Stand> > stands;
private List<Stand> RightStands;
private List<Stand> LeftStands;
Hallway(){
stands = new HashMap();
RightStands = new ArrayList();
LeftStands = new ArrayList();
this.stands.put("Right", RightStands);
this.stands.put("Left", LeftStands);
}
public void addStand(Stand s){
this.stands.get("Right").add(s);
}
}
You need a multi-map, for example from Commons Collections or Guava.
Those will let you map multiple values (Stand1, Stand2, ...) to a single key (e.g. "right").
For example (with Commons Collections):
MultiMap stands = new MultiHashMap();
stands.put("left", new Stand());
stands.put("left", new Stand());
stands.put("right", new Stand());
stands.put("right", new Stand());
stands.put("right", new Stand());
Collection standsOnLeftSide = (Collection) stands.get("left");
I think though that Guava is preferrable because it supports Generics.
Don't use HashTable. It has been deprecated long back. Use TreeMap or HashMap.
List<Stand> right=new ArrayList<Stand>(),left=new ArrayList<Stand>();
Map<String,List<Stand> > stands= new HashMap<String, List<Stand> >();
stands.put("right",right);
stands.put("left",left);
To learn about maps and to decide which Map suits you best read Precisely Concise: Java Maps