How do I iterate through nested TreeMaps? - java

I have a set of 3 nested TreeMaps:
TreeMap<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>> keyDay = new TreeMap<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>>();
TreeMap<Court, TreeMap<Time, String>> keyCourt = new TreeMap<Court, TreeMap<Time, String>>();
TreeMap<Time, String> keyTime = new TreeMap<Time, String>();
which store info for bookings. I'm trying to iterate through them using nested while loops to show all the bookings that have been created, but I need a way in the nested whiles to show only the values which relate to the relevant parent.
Here's what I have:
Iterator listOfDays = keyDay.keySet().iterator();
Iterator listOfCourts = keyCourt.keySet().iterator();
Iterator listOfTimes = keyTime.keySet().iterator();
String output;
while (listOfDays.hasNext()) {
DayOfWeek currentDay = (DayOfWeek) (listOfDays.next());
output += currentDay.toString() + "\n----------\n";
while (listOfCourts.hasNext()){
Court currentCourt = (Court) (listOfCourts.next());
output += currentCourt.toString() + ":\n";
while (listOfTimes.hasNext()){
Time currentTime = (Time) (listOfTimes.next());
String currentName = (String) keyTime.get(currentTime);
output += currentTime.toString() + " - " + currentName + "\n";
}
}
...but as expected (but not wanted), it just iterates through all the entries in each TreeMap til the end.
Can anyone help?

It's not very clear (what are listOfDays, listOfCourts and listOfTimes?), but I guess you need something like this:
for (Map.Entry<DayOfWeek, TreeMap<Court, TreeMap<Time, String>>> dayEntry : keyDay.entrySet()) {
DayOfWeek currentDay = dayEntry.getKey();
output += currentDay.toString() + "\n----------\n";
for (Map.Entry<Court, TreeMap<Time, String>> courtEntry : dayEntry.getValue().entrySet()) {
Court currentCourt = courtEntry.getKey();
output += currentCourt.toString() + ":\n";
for (Map.Entry<Time, String> timeEntry : currentCourt.getValue().entrySet()) {
Time currentTime = timeEntry.getKey();
String currentName = timeEntry.getValue();
output += currentTime.toString() + " - " + currentName + "\n";
}
}
}
In short, a map can be viewed as a set of map entries, and you can iterate through this entry set. Each entry has a key and a value. Since the value, in your case, is another map, you can repeat this operation on the value.

Related

Index Lucene: How to get PointValues terms for LongPoint field

I'm looking for resolution how to get terms for indexed PointValues by field name. For String it is very simple (my sample code):
IndexReader reader = caseIndexer.getIndexReader();
Fields fields = MultiFields.getFields(reader);
Iterator<String> names = fields.iterator();
Map<String, Terms> map = new HashMap<>();
while (names.hasNext()) {
String name = names.next();
// logger.info("->>fieldName: {}", name);
Terms terms = fields.terms(name);
map.put(name, terms);
TermsEnum termsEnum = terms.iterator();
BytesRef text;
while ((text = termsEnum.next()) != null) {
System.out.println("field=" + name + "; text=" + text.utf8ToString());
}
}
I know how to get simple statistics like max and min value (sample code):
List<FieldInfo> allFields = new ArrayList<>();
for (LeafReaderContext ctx : reader.leaves()) {
LeafReader lr = ctx.reader();
Iterator<FieldInfo> infos = lr.getFieldInfos().iterator();
PointValues values = lr.getPointValues();
while (infos.hasNext()) {
FieldInfo info = infos.next();
allFields.add(info);
if (DocValuesType.SORTED_NUMERIC.equals(info.getDocValuesType())) {
final int numDimensions = values.getNumDimensions(info.name);
final int numBytesPerDimension = values.getBytesPerDimension(info.name);
byte[] leafMinValue = values.getMinPackedValue(info.name);
long size = values.size(info.name);
byte[] leafMaxValue = values.getMaxPackedValue(info.name);
long minValueLong = NumericUtils.sortableBytesToLong(leafMinValue, 0);
long maxValueLong = NumericUtils.sortableBytesToLong(leafMaxValue, 0);
double minValueDouble = NumericUtils.sortableLongToDouble(minValueLong);
System.out.println("field=" + info.name + "; minValueLong=" + minValueLong + "; maxValueLong="
+ maxValueLong + "; minValueDouble=" + minValueDouble + "; numDimensions=" + numDimensions
+ "; numBytesPerDimension=" + numBytesPerDimension + "; size=" + size);
}
}
}
but how to get terms for points?
If you need to get the origin value of a LongPoint Field you need to store the value into a dedicated StoredField as described in LongPoint Field JavaDoc.
In general: Point (range/exact use cases) and DocValues (sorting use cases) fields are used for specific internal lucene usage and the values are not usable for search return values.

how to convert a hash table in string in java

I'm new in java and i want to convert a hash table in the form of a string, with each pair separated by any special character. I'm little confuse how to apply loop on the hash table and extract values from. Please explain me how to do this. Thanks in advance
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
foreach(){
hashstring += key + "=" + hashtable[key] + "|";
}
return hashstring;
}
You can use Map.Entry as follows:
String hashstring= "";
for (Map.Entry<String, String> entry : hashTable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
String seperator = "|";
StringBuilder sb = new StringBuilder();
Set<String> keys = detailHashtable.keySet();
for(String key: keys) {
sb.append(key+"="+detailHashtable.get(key)+ seperator);
}
return sb.toString();
Both the HashMap and HashTable can use Map.Entry to get both key and value simultaneously.
String hashstring= "";
for (Map.Entry<String, String> entry : detailHashtable.entrySet()) {
hashstring += entry.getKey() + "=" + entry.getValue() + "|";
}
Refer the API to know what operations can be used.
http://docs.oracle.com/javase/7/docs/api/java/util/Hashtable.html#entrySet()
public String parseHashtable(Hashtable detailHashtable){
String hashstring= "";
for(Entry<String,String> entry : detailHashtable.entrySet()){
hashstring += entry.getKey() + "=" + entry.getValue() + "| ";
}
return hashstring;
}
Map from which Hashtable extends provides the method Map.entrySet(), which returns a set containing all entries in the map.
for(Map.Entry e : detailHashTable.entrySet()){
Object key = e.getKey();
Object value = e.getValue();
...
}
use entry.getKey().to String() and entry.getValue().toString();

Android: Get the entire array the value/key is in ArrayList<HashMap<String, String>>

I am trying to get v8 from the third array inside following arraylist
String[][] test = {
{"v1","v2","v3","v4","v5","v6","v7"},
{"v1","v2","v3","v4","v5","v6","v7"},
{"v1","v2","v3","v4","v5","v6","v7", "v8"}
};
ArrayList<String[]> test2= new ArrayList<String[]>(Arrays.asList(test));
Log.e("v1: ", "" + test2.get(0));
for (int j = 0; j <= test2.size(); j++) {
for (String[] arrays: test2) {
for (String string2 : arrays) {
if (string2.equalsIgnoreCase("v8")) {
Log.e("LOOOOOOOOOG", "" + test2.indexOf("v8")); // 3
}else {
Log.e("LOOOOOOOOOG", "Cant find it!!");
}
}
}
}
How would i do this?
I currently just get either -1 or Cant find it!!
I am trying to solve the above problem to solve the following HashMap problem.
public static void updateJSONdata() {
mEmailList = new ArrayList<HashMap<String, String>>();
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(READ_EMAILS_URL);
try {
mEmails = json.getJSONArray("info");
// looping through all emails according to the json object returned
for (int i = 0; i < mEmails.length(); i++) {
JSONObject c = mEmails.getJSONObject(i);
// gets the content of each tag
String email = c.getString(TAG_EMAIL);
String firstName = c.getString(TAG_FNAME);
String lastName = c.getString(TAG_LNAME);
String address = c.getString(TAG_ADDRESS);
String phoneNumber = c.getString(TAG_PHONE);
String city = c.getString(TAG_CITY);
String state = c.getString(TAG_STATE);
String zip = c.getString(TAG_ZIP);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_EMAIL, email);
map.put(TAG_FNAME, firstName);
map.put(TAG_LNAME, lastName);
map.put(TAG_ADDRESS, address);
map.put(TAG_PHONE, phoneNumber);
map.put(TAG_CITY, city);
map.put(TAG_STATE, state);
map.put(TAG_ZIP, zip);
// adding HashList to ArrayList
mEmailList.add(map);
for (HashMap<String, String> maps : mEmailList){
for (Entry<String, String> mapEntry : maps.entrySet()){
String key = mapEntry.getKey();
String value = mapEntry.getValue();
if (value.equals(passedEmail)) {
Log.e("Is this email in the database?", value + " Is in the database!!!");
int index = map.get(key).indexOf(value);
Log.e("mEmailList: ", "" + mEmailList);
// String[] test = mEmailList.indexOf(value);
fullName = mEmailList.get(index).get(TAG_FNAME) +
" " +
mEmailList.get(index).get(TAG_LNAME);
mPhoneNumber = mEmailList.get(index).get(TAG_PHONE);
mAddress = mEmailList.get(index).get(TAG_ADDRESS) + " " +
mEmailList.get(index).get(TAG_CITY) + " " +
mEmailList.get(index).get(TAG_STATE) + " " +
mEmailList.get(index).get(TAG_ZIP);
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
It looks like you want the index within the list that contains a map that has a specific email address as one of the values. For that purpose you need to call indexOf on the list, and pass to it a Map.
Something like : mEmailList.indexOf(map).
What you are doing is searching for the index of the first occurrence of a sub-string within another String. That won't give you an index within the list.
In addition, it looks like you are mixing the code that creates the list of maps with the code that searches the list for a specific email.
You are getting -1 because of
test2.indexOf("v8")
The ArrayList test2 contains arrays String[], it doesn't containg "v8". test2, for example, contains { "v1", "v2", "v3", "v4", "v5", "v6", "v7", "v8" }, but not "v8".
Note: The methods String#indexOf() and ArrayList#indexOf() are different, so you should read their specification before using them.

write key and values from map to a file

With the code below, I am trying to write the key and values of the male and female map to an existing file.
But it shows the following error.
Can somebody help me please.
ERROR# Map.Entry entry = (Map.Entry) entryIter.next();
java.util.NoSuchElementException
at java.util.LinkedHashMap$LinkedHashIterator.nextEntry(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at java.util.LinkedHashMap$EntryIterator.next(Unknown Source)
at test.main(test.java:83)
Code
public static void main(String[] args) {
Map<String, List<String>> MaleMap = new LinkedHashMap<String, List<String>>();
Map<String, List<String>> FemaleMap = new LinkedHashMap<String, List<String>>();
try {
Scanner scanner = new Scanner(new FileReader(".txt"));
while (scanner.hasNextLine()) {
String nextLine = scanner.nextLine();
String[] column = nextLine.split(":");
if (column[0].equals("Male") && (column.length == 4)) {
MaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
} else if (column[0].equals("Female") && (column.length == 4)) {
FemaleMap.put(column[1],
Arrays.asList(column[2], column[3]));
}
}
Set<Entry<String, List<String>>> entries = MaleMap.entrySet();
Iterator<Entry<String, List<String>>> entryIter = entries.iterator();
while (entryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object key = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object maleName = key;
Object maleAge = null;
Object maleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(key + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object maleName = key;
Object maleAge = value1;
Object maleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write(maleAge + "." + maleID + "##;" + "\n"
+ " :class :" + maleName);// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Set<Entry<String, List<String>>> Fentries = FemaleMap.entrySet();
Iterator<Entry<String, List<String>>> FentryIter = Fentries.iterator();
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) entryIter.next();
Object Fkey = entry.getKey(); // Get the key from the entry.
List<String> value = (List<String>) entry.getValue();
Object value1 = " ";
Object value2 = " ";
int counter = 0;
for (Object listItem : (List) value) {
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = null;
Object femaleID = null;
if (counter == 0) {// first pass assign value to value1
value1 = listItem;
counter++;// increment for next pass
} else if (counter == 1) {// second pass assign value to value2
value2 = listItem;
counter++;// so we dont keep re-assigning listItem for further iterations
}
}
System.out.println(Fkey + ":" + value1 + "," + value2);
scanner.close();
Writer writer = null;
Object femaleName = Fkey;
Object femaleAge = value1;
Object femaleID = value2;
try {
String filename = ".txt";
FileWriter fw = new FileWriter(filename, true); // the true will append the new data
fw.write("map:" + femaleName + " a :Bridge;" + "\n"
+ ":property" + femaleAge + ";" + "\n"
+ ":column" + " " + femaleID + " " + ";");// appends the string to the file
fw.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
Map.Entry entry = (Map.Entry) entryIter.next(); in your second loop is breaking.
After the first while loop that iterates through the males, your iterator has reached the end of the set, and will break when you try to call next().
What you actually want to do is iterate through your females.
Change the line to iterate with your FentryIter:
while (FentryIter.hasNext()) {
Map.Entry entry = (Map.Entry) FentryIter.next();
This is most likely the result of copy-paste code, and you need to be careful when doing this. I would recommend re-factoring your code since so much of it is duplicated.

Displaying the contents of a Map over iterator

I am trying to display the map i have created using the Iterator.
The code I am using is:
private void displayMap(Map<String, MyGroup> dg) {
Iterator it = dg.entrySet().iterator(); //line 1
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
it.remove();
}
}
Class MyGroup and it has two fields in it, named id and name.
I want to display these two values against the pair.getValue().
The problem here is Line 1 never gets executed nor it throws any exception.
Please Help.
PS: I have tried every method on this link.
Map<String, MyGroup> map = new HashMap<String, MyGroup>();
for (Map.Entry<String, MyGroup> entry : map.entrySet()) {
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
using iterator
Map<String, MyGroup> map = new HashMap<String, MyGroup>();
Iterator<Map.Entry<String, MyGroup>> entries = map.entrySet().iterator();
while (entries.hasNext()) {
Map.Entry<String, MyGroup> entry = entries.next();
System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
}
For more iteration information see this link

Categories

Resources