in my scenario the hashTable is like this
AId=1
BId=1
catalogId=10053
reason_1=RET-KP
reason_2=RET-KP
quantity_1=1.0
ItemId_1=468504
quantity_2=1.0
ItemId_2=468505
Now i need to delete all _i things when reason_i=RET-KP
ie. delete ItemId_1 & quantity_1
Where reason_i is reason_1,reason_2
So how i can iterate this hashTable and delete the keys(dynamic) based on their values and storing it in hashTable again.
Check this will solve your problem .
package com.loknath.lab;
public class HashTableDemo {
public static void main(String args[]) {
Hashtable htable = new Hashtable(3);
boolean deleteStatus;
ArrayList<String> list = new ArrayList<String>();
// populate the table
htable.put("AId", 1);
htable.put(" catalogId", 2);
htable.put(" ItemId_1", 43);
htable.put("ItemId_2", 43);
htable.put("bid", 54.45);
Set<String> keys = htable.keySet();
for (String key : keys) {
System.out.println(key);
deleteStatus = check(key);
if (deleteStatus) {
list.add(key);
}
}
for (String string : list) {
htable.remove(string);
}
}
public static boolean check(String key) {
boolean status = false;
status = key.contains("_");
return status;
}
}
Related
I have data of tracks & tracklinks like folowing:
trackname - abc
links - www.abc.com
www.abc1.com
www.abc2.com
trackname - xyz
links - www.xyz.com
www.xyz1.com
www.xyz2.com
I want to make array with in array in Java. so final array would be:
trackdata = {
[0] {
[trackname] = 'abc',
[tracklinks] = {
[0] = "www.abc.com";
[1] = "www.abc1.com";
[2] = "www.abc2.com";
}
},
[1] {
[trackname] = 'xyz',
[tracklinks] = {
[0] = "www.xyz.com";
[1] = "www.xyz1.com";
[2] = "www.xyz2.com";
}
}
I have tried to make this using ArrayList, Map but not succeed.
Map<String,String> map = new HashMap<>();
map.put("trackname", "abc");
ArrayList<String> myLinks= new ArrayList<>();
myLinks.add("www.abc.com");
myLinks.add("www.abc1.com");
myLinks.add("www.abc2.com");
map.put("tracklinks", myLinks);
please help me here.
Consider using a multimap, a map whose values are list objects:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
public class Starter {
public static void main(String[] args) {
Map<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
ArrayList<String> myLinks= new ArrayList<>();
myLinks.add("www.abc.com");
myLinks.add("www.abc1.com");
myLinks.add("www.abc2.com");
map.put("abc", myLinks);
System.out.println(map); // {abc=[www.abc.com, www.abc1.com, www.abc2.com]}
}
}
You should create a class and then access the properties like you want.
class TrackData {
private String trackme;
private List<String> trackLink;
public String getTrackme() {return trackme;}
public void setTrackme(String trackme) {this.trackme = trackme;}
public List<String> getTrackLink() {return trackLink;}
public void setTrackLink(List<String> trackLink) {this.trackLink = trackLink;}
}
To access it:
#Test
void arrayInArray_Test1() {
List<TrackData> trackData = new ArrayList<>();
trackData.add(new TrackData(){{
setTrackme("abc");
setTrackLink(new ArrayList<String>(){{
add("www.abc.com");
add("www.abc1.com");
add("www.abc2.com");
}});
}});
trackData.add(new TrackData(){{
setTrackme("xyz");
setTrackLink(new ArrayList<String>(){{
add("www.xyz.com");
add("www.xyz1.com");
add("www.xyz2.com");
}});
}});
System.out.println(trackData);
}
If you are using a newer Java version, you can create a record instead of a class.
You can achieve as follows
public class TrackTest {
public static void main(String[] args) {
List<Tracks> trackList = new ArrayList<>();
Tracks track1 = new Tracks("abc");
track1.getTrackLinks().add("www.abc.com");
track1.getTrackLinks().add("www.abc1.com");
track1.getTrackLinks().add("www.abc2.com");
Tracks track2 = new Tracks("xyz");
track2.getTrackLinks().add("www.xyz.com");
track2.getTrackLinks().add("www.xyz1.com");
track2.getTrackLinks().add("www.xyz2.com");
trackList.add(track1);
trackList.add(track2);
System.out.println(trackList);
}
static class Tracks{
private String trackName;
private List<String> trackLinks;
public Tracks(String trackName) {
this.trackName = trackName;
this.trackLinks = new ArrayList<>();
}
public Tracks(String trackName, List<String> trackLinks) {
this.trackName = trackName;
this.trackLinks = trackLinks;
}
public String getTrackName() {
return trackName;
}
public List<String> getTrackLinks() {
return trackLinks;
}
#Override
public String toString() {
return "Tracks [trackName=" + trackName + ", trackLinks=" + trackLinks + "]";
}
}
}
Let me know, if you want other approach.
how are u?
Why u dont do this.
Create class named URL, for example.
public class Url(){
//atributes
String domain;
String url;
//Contructor
public class URL(String domain, String url){
this.domain = domain;
this.url = url;
}
}
In ur main.class, u can create one Arraylist to saves ur instaces of URL.
public static void newURL(){
String domain, url;
Scanner keyboard = new Scanner(System.in);
//ask domain, i will use an example.
System.out.println("What is domain of URL?");
domain = keyboard.nextLine();
System.out.println("What is url?");
url = keyboard.nextLine;
//now, u have atributes of new url
URL url = new URL(domain,url);
}
What its ur objective? It's important question.
If is for simple control in a little program, u can do this
I tried first to put all Classe(key) and SuperClasses(value :ArrayList, direct superClasses) of the ontology (I want that the last element of the ontology be the root of my treeView) in a HashMap (hm).
However I don't know how to put properly this hashmap in a TreeView.
A recursive tree would suit much better but I don't know how to do that. (I have a method who convert a recursive data structure in a treeView)
Would anyone be able to give me some clues for my problem?
Thanks !
method who return the hashmap :
public HashMap<String, ArrayList<String>> getClassesHashMap() {
HashMap<String, ArrayList<String>> hm = new HashMap<String, ArrayList<String>>();
OWLReasonerFactory reasonerFactory = new StructuralReasonerFactory();
OWLReasoner reasonerFactory3 = reasonerFactory.createReasoner(ontology);
OWLDataFactory fac3 = ontology.getOWLOntologyManager().getOWLDataFactory();
for (String s : getClassesName()) {
IRI docIRI = IRI.create(ontology.getOntologyID().getOntologyIRI().get() + "#" + s);
OWLClass pizza = fac3.getOWLClass(docIRI);
NodeSet<OWLClass> subClses = reasonerFactory3.getSuperClasses(pizza, true);
Set<OWLClass> clses = subClses.getFlattened();
System.out.println("Subclasses of " + s + " : ");
//instanciate the hashmap
for (OWLClass cls1 : clses) {
//cls1.getIRI().getShortForm() is the name of an ontology classes in String
//all the classe is a key, and their superclasses is the value
if (!cls1.getIRI().getShortForm().equals("Thing")) {
if (!hm.containsKey(s)) {
hm.put(s, new ArrayList<String>());
}
hm.get(s).add(cls1.getIRI().getShortForm());
System.out.println(" " + cls1.getIRI().getShortForm());
}
System.out.println();
}
}
// Tree<String> res = new Tree<String>("");
return hm;
}
Method who instanciate the TreeView
private void initTreeView() throws OWLException {
// TreeItem<String> root = new TreeItem<String>("Private_Policy");
tree.setFixedCellSize(25);
//Privacy Policy is the Ontology classe I Use
TreeItem<String> root = new TreeItem<String>("PrivacyPolicy");
root.setExpanded(true);
OntologieDAO ont = new OntologieDAO("WotPriv.owl");
//hashmap of the ontology
HashMap<String, ArrayList<String>> hm = ont.getClassesHashMap();
TreeItem<String> children = new TreeItem<String>("");
System.out.println(hm);
int i = 0;
//work only for my ontology
for (String s : hm.get(root.getValue())) {
TreeItem<String> tI = new TreeItem<String>(s);
root.getChildren().add(tI);
if (hm.containsKey(s)) {
for (String s1 : hm.get(s)) {
TreeItem<String> n = new TreeItem<String>(s1);
TreeItem<String> tI1=root.getChildren().get(root.getChildren().indexOf(tI));
tI1.getChildren().add(n);
if (hm.containsKey(s1)) {
for (String s2 : hm.get(s1)) {
tI1.getChildren().get(tI1.getChildren().indexOf(n)).getChildren().add(new TreeItem<String>(s2));
}}
}
}
}
tree.setRoot(root);
tree.getSelectionModel().setSelectionMode(SelectionMode.MULTIPLE);
System.out.println(ont.getClassesName());
}
A recursive data structure and a method to convert it in treeview :
import java.util.HashSet;
import java.util.Set;
public class MyType<N> {
private Set<MyType<N>> children = new HashSet<>();
private N Value;
public MyType(N value) {
super();
Value = value;
}
public Set<MyType<N>> getChildren() {
return children;
}
public void setChildren(Set<MyType<N>> children) {
this.children = children;
}
public N getValue() {
return Value;
}
public void setValue(N value) {
Value = value;
}
}
private TreeItem<MyType<String>> buildSubtree(MyType<String> root) {
TreeItem<MyType<String>> result = new TreeItem<>(root);
if (root.getChildren() != null) {
for (MyType<String> child : root.getChildren()) {
result.getChildren().add(buildSubtree(child));
}
}
return result;
}
(Image) Result I want to have (I already have it but my code is really dirty and would'nt work with other ontology)
my task is to make a synonym dictionary using HashMaps and Sets.
I have the following code in my main method:
public static void main(String[] args) {
addSynonym("casa", "imobil");
addSynonym("casa", "cladire");
addSynonym("casa", "locuinta");
addSynonym("casa", "camin");
addSynonym("casa", "domiciuliu");
addSynonym("jucarie", "joc");
addSynonym("jucarie", "marioneta");
addSynonym("jucarie", "papusa");
addSynonym("jucarie", "pantin");
addSynonym("om", "barbat");
addSynonym("om", "persoana");
afisarearray(getSynonyms("camin"));
}
One Method to insert the synonyms and the keys:
static Map<String, ArrayList<String>> synonymTable = new HashMap<String, ArrayList<String>>();
public static void addSynonym(String word, String synonym) {
ArrayList<String> checklist = synonymTable.get(word);
if (checklist == null) {
ArrayList<String> temporarylist = new ArrayList<String>();
temporarylist.add(synonym);
synonymTable.put(word, temporarylist);
} else {
synonymTable.get(word).add(synonym);
}
}
One Method to display an ArrayList:
public static void afisarearray(ArrayList<String> list) {
if (list != null) {
for (String s : list) {
System.out.println(s + "\n");
}
} else {
System.out.println("Empty list");
}
};
I want to find all the synonyms of a word for example the word "camin". And I wrote the following Method to do it, but it's not working, it is returning an empty set of keys:
public static ArrayList<String> getSynonyms(String word) {
if (word == "") {
System.out.println("No word to serach for ");
return null;
} else {
Set<String> keySet = new HashSet<String>();
for (Map.Entry<String, ArrayList<String>> entry : synonymTable.entrySet()) {
if (entry.getValue().equals(word)) {
keySet.add(entry.getKey());
}
}
if (keySet.isEmpty()) {
System.out.println("No keys found");
return null;
} else {
ArrayList<String> newlist = new ArrayList<String>();
for (String s : keySet) {
newlist.addAll(synonymTable.get(s));
}
return newlist;
}
}
}
The problem is inside this if:
if (entry.getValue().equals(word))
is a comparison between an ArrayList and a string.
I don't know how to correct it.
Try this, I also cleaned up your code a bit for readability
public static List<String> getSynonyms(String word) {
if (word == null || word.trim().isEmpty()) {
System.out.println("No word to serach for ");
return null;
}
Set<String> keySet = new HashSet<String>();
for (Map.Entry<String, List<String>> entry : synonymTable.entrySet()) {
if (entry.getValue().contains(word)) {
keySet.add(entry.getKey());
}
}
if (keySet.isEmpty()) {
System.out.println("No keys found");
return null;
}
//de-dupe and sort
Collection<String> terms = new TreeSet<>();
for (String s : keySet) {
terms.addAll(synonymTable.get(s));
}
return new ArrayList<>(terms);
}
I have MaterailInfo and StyleInfo, I want to set styleDescription based on StyleNumber matching with materialNumber. I am using 2 for loops, is there any alternative solution?
MaterailInfo:
class MaterailInfo {
private String materialNumber;
private String materialDescription;
public MaterailInfo(String materialNumber, String materialDescription) {
this.materialNumber = materialNumber;
this.materialDescription = materialDescription;
}
// getter setter methods
}
StyleInfo:
class StyleInfo {
private String StyleNumber;
private String styleDescription;
public StyleInfo(String styleNumber, String styleDescription) {
StyleNumber = styleNumber;
this.styleDescription = styleDescription;
}
// getter setter toString methods
}
TEst12:
public class TEst12 {
public static void main(String[] args) {
List<MaterailInfo> mList = new ArrayList<MaterailInfo>();
mList.add(new MaterailInfo("a", "a-desc"));
mList.add(new MaterailInfo("b", "b-desc"));
mList.add(new MaterailInfo("c", "c-desc"));
List<StyleInfo> sList = new ArrayList<StyleInfo>();
sList.add(new StyleInfo("a", ""));
sList.add(new StyleInfo("b", ""));
sList.add(new StyleInfo("c", ""));
for (MaterailInfo m : mList) {
for (StyleInfo s : sList) {
if (s.getStyleNumber().equals(m.getMaterialNumber())) {
s.setStyleDescription(m.getMaterialDescription());
}
}
}
System.out.println(sList);
}
}
If you use a Map instead of a List to store your data, you can get away with doing only a single loop:
Map<String, String> mMap = new HashMap<String, String>();
mMap.put("a", "a-desc");
mMap.put("b", "b-desc");
mMap.put("c", "c-desc");
Map<String, String> sMap = new HashMap<String, String>();
sMap.put("a", "");
sMap.put("b", "");
sMap.put("c", "");
for (Map.Entry<String, String> entry : mMap.entrySet()) {
sMap.put(entry.getKey(), mMap.get(entry.getKey());
}
This code will leave the style description empty if the style number does not match any known material number.
If your numbers can't have duplicates, using a HashMap instead of classes can be a bit faster.
import java.io.*;
import java.util.*;
import java.util.Map.Entry;
public class Demo {
public static void main(String[] args) {
HashMap<String, String> mList = new HashMap();
HashMap<String, String> sList = new HashMap();
mList.put("a", "a-desc");
mList.put("b", "b-desc");
mList.put("c", "c-desc");
sList.put("a", "");
sList.put("b", "");
sList.put("c", "");
Iterator entries = sList.entrySet().iterator();
while (entries.hasNext()) {
Entry entry = (Entry) entries.next();
if (mList.containsKey(entry.getKey())) {
sList.put((String) entry.getKey(), mList.get(entry.getKey()));
}
}
for (Map.Entry<String, String> entry : sList.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
}
You can do this using one for loop like this
for (int i = 0; i < mList.size(); i++) {
sList.get(i).setStyleDescription(mList.get(i).getMaterialDescription());
}
Note: i am assuming you have balanced lists in term of size.
I have two Hashmaps filled here:
Properties properties = new Properties();
try {
properties.load(openFileInput("xmlfilesnames.xml"));
} catch (IOException e) {
e.printStackTrace();
}
for (String key : properties.stringPropertyNames()) {
xmlFileMap.put(key, properties.get(key).toString());
}
try {
properties.load(openFileInput("comparexml.xml"));
} catch (IOException e) {
e.printStackTrace();
}
for (String key : properties.stringPropertyNames()) {
compareMap.put(key, properties.get(key).toString());
}
Declaration:
public Map<String,String> compareMap = new HashMap<>();
public Map<String, String> xmlFileMap = new HashMap<>();
they look like:
How can I check if the job_id changed of maybe if it's null?
Sometimes the job_id doesn't really exists. So the job_id is missing in them.
And Sometimes in compareMap are more then one job_id
How can I compare just the job_id's and get a boolean value when compared?
Seems that you want to find the map key based on specific pattern. This can be done by iterating over all keys:
private static String PREFIX = "<job_id>";
private static String SUFFIX = "</job_id>";
public static String extractJobId(Map<String, ?> map) {
for(String key : map.keySet()) {
if(key.startsWith(PREFIX) && key.endsWith(SUFFIX))
return key.substring(PREFIX.length(), key.length()-SUFFIX.length());
}
// no job_id found
return null;
}
If you may have several job_id keys and want to check whether all of them are the same, you can build an intermediate set instead:
public static Set<String> extractJobIds(Map<String, ?> map) {
Set<String> result = new HashSet<>();
for(String key : map.keySet()) {
if(key.startsWith(PREFIX) && key.endsWith(SUFFIX))
result.add(key.substring(PREFIX.length(), key.length()-SUFFIX.length()));
}
return result;
}
Now you can use this method to compare job_id of different maps:
if(Objects.equals(extractJobIds(xmlFileMap), extractJobIds(compareMap))) {
// ...
}