Hello I am trying to pass to my jsp page two sorted Lists which I get from the database like that
#RequestMapping(value = "/sortDate", method= RequestMethod.GET)
public void sortedLists(Model model, HttpSession session){
List<Song> songsByDate;
try {
songsByDate = SongDAO.getInstance().getAllSongs();
Collections.sort(songsByDate, new UploadTimeComparator());
session.setAttribute("songs", songsByDate);
/////////////////////////////////
List<Song> songsByLikes;
try {
songsByLikes = SongDAO.getInstance().getAllSongs();
Collections.sort(songsByLikes, new LikesComparator());
session.setAttribute("songs2", songsByLikes);
}}}
However the problem is since I use getInstance() , songs and songs2 are the same Lists sorted by Likes,how can I overcome this problem?
You need to copy each "all songs" list to a new array list, which you can then proceed to sort.
So:
List<Song> songsByDate = new ArrayList<>( SongDAO.getInstance().getAllSongs() );
Collections.sort( songsByDate, new UploadTimeComparator() );
List<Song> songsByLikes = new ArrayList<>( SongDAO.getInstance().getAllSongs() );
Collections.sort( songsByLikes, new LikesComparator() );
Related
I've got this JSON string:
String json = "{\"countries\":{\"2\":\"China\",\"3\":\"Russia \",\"4\":\"USA\"},\"capitals\":{\"2\":Beijing,\"4\":null,\"3\":Moscow}}";
I converted string to HashMap, using this:
HashMap<String,Object> map = new Gson().fromJson(json, new TypeToken<HashMap<String, Object>>(){}.getType());
System.out.println(map.get("countries")+"#####"+map.get("capitals"));
And now my output is:
{2=China, 3=Russia , 4=USA}#####{2=Beijing, 4=null, 3=Moscow}
I would like to connect this values by numbers. I want to create two ArrayList like this:
A)- [China,Russia,USA]
B)- [Beijing,Moscow,null]
How can i do it?
First, you need to cast map.get("label") to LinkedTreeMap<Integer, String>, then create new ArrayList with it's values
String json = "{\"countries\":{\"2\":\"China\",\"3\":\"Russia \",\"4\":\"USA\"},\"capitals\":{\"2\":Beijing,\"4\":null,\"3\":Moscow}}";
HashMap<String,TreeMap<Integer, String>> map = new Gson().fromJson(json, new TypeToken<HashMap<String, TreeMap<Integer, String>>>(){}.getType());
ArrayList<String> countries = new ArrayList<>(map.get("countries").values());
System.out.println(countries);
ArrayList<String> capitals = new ArrayList<>(map.get("capitals").values());
System.out.println(capitals);
You can iterate over the country keyset to fill the capital array:
List<String> countries = new ArrayList<>(countriesMap.values());
List<String> capitals = new ArrayList<>();
for (String countryKey : countriesMap.keySet()) {
capitals.add(capitalsMap.get(countryKey));
}
im actually working on a Project for my University.
In a case, the user is able to produce new Objects and my problem is, that ALL needed Objects are from a SubClass of ASpaceShip.
The Question is now how to create dynamic objects with a array of String Inputs from the User.
One of the Problems is, that there will be more SubClasses in the Future and a switch for 50+ subclasses ... naaaa
Example:
class SpaceShipOne extends ASpaceShip
class SpaceShipTwo extends ASpaceShip
class SpaceShipSpecial extends ASpaceShip
class SpaceShipN extends ASpaceShip
Input from User, Stringarray
input[0] = "SpaceShipTwo";
input[1] = "SpaceShipSpecial";
input[n] = "AlreadyExistingClassName";
Needed:
ArrayList<ASpaceShip> shipList; // Containts all Objects from the User input.
I would love to just loop the userinput and
ASpaceShip ship = new (input[0])(); // casting the class with the String name
But this sadly doesnt work ...
Inet isnt giving much help on this topic or stuff that could work but is deprecated :(
Some ideas here?
Code of Servlet
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Required Objects
HttpSession session = request.getSession();
Player player = (Player)session.getAttribute("player");
TechTree techtree = player.getTechTree(); // Ships need their TechTree
ArrayList<ASpaceShip> ships = new ArrayList<ASpaceShip>(); // to save Ships which are build
ArrayList<ASpaceShip> allResearchedShips = techtree.getAllResearchedShips(); // to save Ships which are build
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String shipName = parameterNames.nextElement();
String[] paramSValue = request.getParameterValues(shipName);
int pVal = Integer.parseInt(paramSValue[0]);
if (hasShip(allResearchedShips, shipName)) {
if (pVal > 0) {
//ASpaceShip newShip = new Class<shipName>(techtree,1);
}
}
}
} // End doPost
If I understand well your question, you would simply need to have a switch / case statement or an if etc, checking user input string and constructing the appropriate object using the proper subclass. Then all constructed object could be added to an ArrayList<ASpaceShip> , eg holding all objects that extend ASpaceShip
ASpaceShip a = null;
ArrayList<ASpaceShip> myList = new ArrayList<>();
for (String s : inputArray) {
if ("SpaceShipOne".equals(s)) a = new SpaceShipOne();
if ("SpaceShipTwo".equals(s)) a = new SpaceShipTwo();
...
myList.add(a);
}
UPDATE:
Using reflection :
ASpaceShip a = null;
ArrayList<ASpaceShip> myList = new ArrayList<>();
String[] array = {"SpaceShipTwo","SpaceShipSpecial"};
for (String className : array) {
Class aClass = Class.forName("yourPackagePath" + className); // need to pass full class name here
a = (ASpaceShip)aClass.newInstance();
myList.add(a);
}
for (ASpaceShip as : myList) System.out.println(as.getClass().getSimpleName());
I'm trying to create a meeting with attendees in Odoo, The attendees fields is many2many field. if I don't add it to the request, the meeting is created just fine without attendees. However , if I add the "partner_ids" key that corresponds to the many2many field. The meeting does not appear. Here are samples of what I tried :
// Attempt 1 : add them as an integer array
List<Integer> partnerIds= new ArrayList<>();
partnerIds.add(15403);
partnerIds.add(7567);
partnerIds.add(7564);
// Attempt 2 : add them in a hashmap array;
List<HashMap<String,Integer>> hashMapList= new ArrayList<>();
HashMap<String,Integer> hashMap= new HashMap<>();
hashMap.put("id",15401);
HashMap<String,Integer> hashMap2= new HashMap<>();
hashMap2.put("id",15400);
HashMap<String,Integer> hashMap3= new HashMap<>();
hashMap3.put("id",15399);
hashMapList.add(hashMap);
hashMapList.add(hashMap2);
hashMapList.add(hashMap3);
attempt 3 : add them into a list of objects as mentioned here
List<Object> testObj= new ArrayList<>();
//Object obj = new Object();
testObj.add(0);
testObj.add(0);
testObj.add(hashMapList);
List<Object> manyToManyRecord = new ArrayList<>();
manyToManyRecord.add(testObj);
Log.d("manyToManyRecord", manyToManyRecord.toString());
OdooValues values = new OdooValues();
values.put("opportunity_id",25619);
values.put("partner_ids", manyToManyRecord);
values.put("name", "App Discussion Meet ");
values.put("start", "2019-03-27 10:00:00");
values.put("stop", "2019-03-27 20:00:00");
values.put("allday", false);
values.put("day", 0);
values.put("user_id", 1);
values.put("active", true);
values.put("recurrent_id", 0);
values.put("x_project_latitude", 0);
values.put("x_project_longitude", 0);
values.put("description", "Test Meeting Description");
client.create("calendar.event", values, new IOdooResponse() {
#Override
public void onResult(OdooResult result) {
int serverId = result.getInt("result");
Log.d("Meeting Id", String.valueOf(serverId));
}
});
So where is the mistake I am making ? Any help with the steps is appreciated!
This solution worked for me :
//The 15401,15400... are static ids that were inputted for testing
values.put("partner_ids", asList(asList(6, 0, asList(15401,15400,15399))));
I'm trying to get genres from a file of movies and then check to see if genre is the same. so if in the file there are movies with the same genre they should be stored in the same array of linklist.
i need check the genre's hashcode and then find out if any other movie in the file hash the same hashcode for genre then place that particular genre in a linked list. so basically I have this so far and i also have a link list class etc and not using java.util
public class LoadingMovies {
private static final int size = 22;
private static HashMap<String, Movies> hash = new HashMap(size);
private static HashEntry<String, Movies> hasher = new HashEntry();
private static List<Movies> linked = new List<>();
public static void loadMovies(String filename) throws FileNotFoundException {
String split = ","; //split with comma
Scanner in = new Scanner(new File(filename));
ArrayList<String> arraylist = new ArrayList<>();
String wordIn;
Movies movie = new Movies();
while (in.hasNextLine()) {
wordIn = in.nextLine();
String splitter[] = wordIn.split(split);
String movieTitle = splitter[0];
String movieGenre = splitter[1];
String ageRating = splitter[2];
double scoreRating = Double.parseDouble(splitter[3]);
movie.setTitle(movieTitle);
movie.setGenre(movieGenre);
movie.setAgeRating(ageRating);
movie.setScoreRating(scoreRating);
//System.out.println(movie.getGenre());
arraylist.add(movie.getGenre);
// hash.find(movie.getGenre().hashCode());
// hash.insert(movie.getGenre().hashCode(), movie);
}
}
}
This is what i have so far. I already read in the file now I want to check to see if a genre (String) in the file is same and then add that genre to link list. how can I do this?
A HashMap<String, List<Movie>> seems to be what you're looking for:
Map<String, List<Movie>> movieGenres = new HashMap<>();
while (in.hasNextLine()) {
// code you have
List<Movie> moviesInThisGenre = moviewGenres.get(genre);
if (moviesInThisGenre == null) {
moviesInThisGenre = new LinkedList<>();
movieGenres.put(genre, moviesInThisGenre);
}
moviesInThisGenre.add(movie);
}
You would need a Map that maps from genre String to Lists of Movies:
HashMap<String, List<Movies>> genres = new Hash...
then when you add a Movie:
String g = movie.getGenre();
if (!genres.containsKey(g)
genres.put(g, new ArrayList<Movies>));
genres.get(g).add(movie);
Explanation
A HashMap stores values for key objects, where each key object can only occur once in the map. Thus, when you want to store multiple movies for one genre String, the value type should be a collection (List, Set, etc.).
e.g.
HashMap<String, Movies> genres ... ;
...
genres.put(g, movie);
will override any Movie value you had for that genre before.
But, since you cannot know at runtime if the genre already exists in your Map, you have to put a new (empty) list for an unknown genre. Any movies with that genre can now be added to that list.
I read a tutorial, and it uses SQLlite and "SimpleCursorAdapter" to fill the list with items.
This is the code the tutorial taught me.
private void fillData() {
// Get all of the notes from the database and create the item list
Cursor c = mDbHelper.fetchAllNotes();
startManagingCursor(c);
String[] from = new String[] { NotesDbAdapter.KEY_TITLE };
int[] to = new int[] { R.id.text1 };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes =
new SimpleCursorAdapter(this, R.layout.notes_row, c, from, to);
setListAdapter(notes);
}
However...what if I want to fill it with XML data? Is it the same method? Can someone give me an example (in code)? thanks.
The example is using a CursorAdapter because a Cursor object is returned by the NotesDbAdapter (if i remember correctly ) fetchAllNotes method. I don't know if there is a way to pass in raw XML to create a list but you can use name/value pairs in a HashMap to create a list using the SimplelistAdapter.
You can parse your xml and or json and build a hash table with it and use that to populate a list. The following example doesn't use xml, in fact it's not dynamic at all, but it does demonstrate how to assemble a list at runtime. It's taken from the onCreate method of an activity that extends ListActivity. The all uppercase values are static constant strings defined at the top of the class, and are used as the keys.
// -- container for all of our list items
List<Map<String, String>> groupData = new ArrayList<Map<String, String>>();
// -- list item hash re-used
Map<String, String> group;
// -- create record
group = new HashMap<String, String>();
group.put( KEY_LABEL, getString( R.string.option_create ) );
group.put( KEY_HELP, getString( R.string.option_create_help ) );
group.put( KEY_ACTION, ACTION_CREATE_RECORD );
groupData.add(group);
// -- geo locate
group = new HashMap<String, String>();
group.put( KEY_LABEL, getString(R.string.option_geo_locate ) );
group.put( KEY_HELP, getString(R.string.option_geo_locate_help ) )
group.put( KEY_ACTION, ACTION_GEO_LOCATE );
groupData.add( group );
// -- take photo
group = new HashMap<String, String>();
group.put( KEY_LABEL, getString( R.string.option_take_photo ) );
group.put( KEY_HELP, getString(R.string.option_take_photo_help ) );
group.put( KEY_ACTION, ACTION_TAKE_PHOTO );
groupData.add( group );
// -- create an adapter, takes care of binding hash objects in our list to actual row views
SimpleAdapter adapter = new SimpleAdapter( this, groupData, android.R.layout.simple_list_item_2,
new String[] { KEY_LABEL, KEY_HELP },
new int[]{ android.R.id.text1, android.R.id.text2 } );
setListAdapter( adapter );