if(Collections.frequency(ItemSet, distinctItemsList) >= support) {
ItemList.addAll(ItemSet);
FrequentItem1.put(ItemList, Collections.frequency(ItemSet, distinctItemsList));
System.out.println(FrequentItem1);
}
the above code is just repeating the transaction instead of giving item followed by frequency
ItemList is the array list of individual transactions
TID. ItemList
Tylenol,Thermometer
water,Milk,Battery
ItemSet is an array list with elements like Tylenol, Thermometer,
Battery etc..i.e the Main function looks like this
try {
Statement statement= connection.createStatement();
String sql="Select distinct TID from transaction";
ResultSet SetTid= statement.executeQuery(sql);
while(SetTid.next()) {
int initialTID= SetTid.getInt("TID");
TID.add(initialTID);
}
System.out.println("TID Items");
for(int initialTID : TID) {
String sqlitem="Select ItemSet from transaction where TID="+ initialTID;
ResultSet setItem= statement.executeQuery(sqlitem);
while(setItem.next()) {
String items= setItem.getString("ItemSet");
//System.out.println("&&&&&&&&"+ items);
ItemList.add(items);
ItemSet=Arrays.asList(items.split(","));
noOfTransaction++;
System.out.println(initialTID+":"+ items);
//System.out.println(initialTID+":"+ ItemList);
}
for(String items : ItemSet) {
System.out.println("&&&&>>"+ items);
if(! distinctItemsList.contains(items)) {
distinctItemsList.add(items);
}
}
System.out.println("No of transaction"+ noOfTransaction);
}
}
DistinctItem list is an array list that contains unique items.
If you are using java-8, below should generate hashmap with word and it's frequency-
Map<String, Long> collect = wordsList.stream().collect(groupingBy(Function.identity(), counting()));
Related
Before i used an ArrayList for this, but because of duplicate Album issues (which i resolved before API29 by using DISTINCT and GROUP BY statements) which are not allowed anymore to use inside a query.
I got values like this in my RecyclerViews Adapter: myArrayList.get(position).getAlbum();
But now that i'm using a HashMap, how can i get a value by position which i get from the adapter?
Code for adding values in Hashmap
HashMap<Integer, Album> albums = new HashMap<>();
String[] projection2 = { MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.IS_MUSIC};
String selection = MediaStore.Audio.Media.IS_MUSIC + "!=0";
String sort = MediaStore.Audio.Media.ALBUM + " COLLATE NOCASE ASC";
cursor = resolver.query(musicUri, projection2, selection, null, sort);
try {
if (cursor != null) {
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
int columnAlbumId = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM_ID);
int columnAlbumName = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.ALBUM);
String albumId = cursor.getString(columnAlbumId);
String albumName = cursor.getString(columnAlbumName);
if(albums.containsKey(albumId) == false){
Album album = new Album(albumId, albumName);
albums.put(albumId, album);
}
cursor.moveToNext();
}
}
}catch (Exception e){
Log.e(TAG, "Exception caught when creating ALBUM!", e);
throw new Exception();
}
By definition the HashMap is not sorted so how about a SortedMap? An implementation of a SortedMap is a TreeMap which sorts the entries according to keys (or a Comparator).
I believe that suits you since your map has integers as keys.
Edit:
You can use a List or whatever collection suits you in your adapter. For example keep a reference to the ids and the albums which is the data that you're interested in displaying through the adapter.
private int[] ids;
private Album[] albums;
As you're passing the data (included in a map) to your adapter then you could extract that data and place it in the array containers so you can take advantage of the index. For example,
public MyAdapter(Map<Integer,Album> data){
ids = new int[map.size()];
albums = new Album[map.size()];
int i = 0;
for (Map.Entry<Integer,Album> e : map.entrySet()){
ids[i] = e.getKey();
albums[i++] = e.getValue();
}
}
Now that you have your arrays you can sort them also if you like and in case you want to grab the 3rd album and its id all you need to do is,
int id = ids[2];
Album album = albums[2];
I have a user list
List<User> usrList1 = new ArrayList<User>();
userList.add(new User("usr1",11,""));
userList.add(new User("usr2",22,""));
userList.add(new User("usr3",33,""));
another User List contains
List<User> usrList2 = new ArrayList<User>();
userList2.add(new User("",11,"add1"));
userList2.add(new User("",22,"add2"));
now how can I merge these two List and get a single list of User using id, considering performance. Consider the size of userList1 and userList2 are around 50.
List<User> usrList = new ArrayList<User>();
userList.add(new User("usr1",11,"add1"));
userList.add(new User("usr2",22,"add2"));
userList.add(new User("usr3",33,""));
This is pretty straight forward for a small list, without considering performance issues and assuming a merge strategy of appending Name and Data fields:
Copy (shallow) list1 into a new list merged
Iterate over list2
For each item in merged check if item in list2 already exists
If the item exists, just update its fields
If it does not exist, append it to the end of merged
Code:
public static List<User> Merge(List<User> list1, List<User> list2) {
List<User> merged = new ArrayList<User>(list1);
for (User user : list2) {
boolean found = false;
for (User u : merged) {
if (u.Id == user.Id) {
found = true;
u.Name += user.Name;
u.Data += user.Data;
break;
}
}
if (!found) {
merged.add(user);
}
}
return merged;
}
You can user HashMap as helper data structure
For key is needed to use user id (integer value in list)
public static void main(String[] args) {
List<User> userList1 = new ArrayList<User>();
userList1.add(new User("usr1", 11, ""));
userList1.add(new User("usr2", 22, ""));
userList1.add(new User("usr3", 33, ""));
List<User> userList2 = new ArrayList<User>();
userList2.add(new User("", 11, "add1"));
userList2.add(new User("", 22, "add2"));
// Insert all elements from first list to hash map
HashMap<Integer, User> userMap = new HashMap<>();
for (User user : userList1) {
userMap.put(user.getId(), user);
}
// Update user elements
for (User user : userList2) {
User update = userMap.get(user.getId());
update.setAddres(user.getAddress());
}
// convert hash map to list
List<User> merge = new ArrayList<>();
merge.addAll(userMap.values());
System.out.println(merge);
}
Note:
HashMap will not preserve the order of elements. If it is needed to merge list be in the same order as userList1 then use LinkedHashMap.
I have two ArrayList sourceMessageList and TargetMessageList. I need to compare both the message list data.
Now lets say List1 - 100 Records. List2 - 1000 records
From List1- 1st record is compared with each record in list2 and then List1- 2nd record is compared with each record in list2.
But list2 is getting the value hasNext() to true for 1st source data in list1.
private void compareMessageList(ArrayList<String> source_messageList, ArrayList<String> target_messageList)
throws Exception {
// TODO Auto-generated method stub
Iterator<String> sourceMessageIterator = source_messageList.iterator();
Iterator<String> targetMessageIterator = null;
while (sourceMessageIterator.hasNext()) {
String sourceMessage = (String) sourceMessageIterator.next();
targetMessageIterator = target_messageList.iterator();
while (targetMessageIterator.hasNext()) {
String targetMessage = (String) targetMessageIterator.next();
if (getCorpValue(sourceMessage).equalsIgnoreCase(getCorpValue(targetMessage))) {
assertXMLEquals(convertSwiftMessageToXML(sourceMessage), convertSwiftMessageToXML(targetMessage));
}
}
}
if (buffer.toString().length() > 0) {
writeDifferenceTofile(buffer.toString());
buffer.delete(0, buffer.length());
throw new CatsException("There are some differences in the files.");
}
System.out.println("Exiting now ...");
}
The above code is taking too much time to execute.
To speed things up:
HashMap<String, String> lowers = new HashMap<String, String>();
for (String source : source_messageList) {
lowers.put(getCorpValue(source).toLowerCase(), source);
}
for (String target : target_messageList) {
final String corpTarget = getCorpValue(target).toLowerCase();
if(lowers.containsKey(corpTarget)) {
assertXMLEquals(
convertSwiftMessageToXML(lowers.get(corpTarget)),
convertSwiftMessageToXML(target)
);
}
}
If we have input file which contains the pair of state and city, there can be multiple cities which belongs to same state. What we have to do is we have to make that single state as key and the cities which belongs to that state as value.
For example, I am reading the following data from a file:
Maharashtra - Pune
Madhyapradesh - Bhopal
Maharashtra - Mumbai
Maharashtra - Nagpur
Here Maharashtra will become a key, with Pune, Mumbai and Nagpur becoming values. What I did is first I split The data into state and city. I am now trying to store the states in a list and then check the list but I am stuck.
How can I make the Maharashtra as key and Pune, Mumbai and Nagpur as its respective values? Like this:
Maharashtra- Pune, Mumbai, Nagpur.
This is what I have so far:
public class DataManagerImpl implements DataManager {
#Override
public Map<String, List<String>> populateCityDataMap(String fileName)
throws FileNotFoundException {
// TODO Auto-generated method stub
Map<String, List<String>> map = new HashMap<String, List<String>>();
List<String> valSetOne = new ArrayList<String>();
List<String> list=null;
String nameAndRollNumber=null;
String[] nameAndRollNumbers =null;
String State=null;
Scanner s = null;
try {
s = new Scanner(new File("F:\\Participant_Workspace\\Q4\\CityStateLocator\\StateCityDetails.txt"));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
while (s.hasNext()) {
nameAndRollNumber = s.nextLine();
nameAndRollNumbers = nameAndRollNumber.split("-");
State = nameAndRollNumbers[0];
String City=nameAndRollNumbers[1];
/*System.out.println(valSetOne);
map.put(State,valSetOne);*/
System.out.println(State+" "+City);
list.add(State);
}
/*Iterator<String> CrunchifyIterator = list.iterator();
while (CrunchifyIterator.hasNext()) {
System.out.println(CrunchifyIterator.next());
}*/
System.out.println(list);
return null;
}
}
You need something like map with key as state (which is a String) and value as list of cities (i.e. list of strings). So your data structure should be something like:
Map<String, List<String>> map ...
List<String> cities = map.get(state);
if (cities == null) {
cities = new ArrayList<String>();
map.put(state, cities);
}
cities.add(city);
I have a method in the model that creates an ArrayList array me from a resultset, I need is cross it from jsp, I could not do, any help?
This is the code of the arraylist
public ArrayList listar(){
String sql="select * from eventos";
ArrayList lista=new ArrayList();
try {
st=con.createStatement();
rs=st.executeQuery(sql);
int NumColumnas=getRows(rs);
while(rs.next()){
String Fila[]=new String [NumColumnas];
for(int x=0;x<NumColumnas;x++){
Fila[x]=rs.getObject(x+1).toString();
}
lista.add(Fila);
}
} catch (SQLException ex) {
Logger.getLogger(EventosBean.class.getName()).log(Level.SEVERE, null, ex);
}
return lista;
}
From the jsp I have this code and I returned values in this format [Ljava.lang.String;#39dc94a4 [Ljava.lang.String;#5d013b69
EventosBean ev=new EventosBean();
ArrayList<EventosBean>arrayList=ev.listar();
out.println(arrayList.size());
Iterator<EventosBean> iterator = arrayList.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Something is wrong. In your listar method, you are returning a ArrayList . This ArrayListcontains obejcts of type String[]. You are capturing this output in a ArrayList<EventosBean>, which expects objects of type EventosBean.
If you are looking to print content of the String[] added in listar returned ArrayList on JSP, make few changes in your code as shown below.
public ArrayList<String[]> listar(){
String sql="select * from eventos";
ArrayList<String[]> lista=new ArrayList<String[]>();
try {
st=con.createStatement();
rs=st.executeQuery(sql);
int NumColumnas=getRows(rs);
while(rs.next()){
String Fila[]=new String [NumColumnas];
for(int x=0;x<NumColumnas;x++){
Fila[x]=rs.getObject(x+1).toString();
}
lista.add(Fila);
}
} catch (SQLException ex) {
Logger.getLogger(EventosBean.class.getName()).log(Level.SEVERE, null, ex);
}
return lista;
}
and in your class where you are calling listar
EventosBean ev=new EventosBean();
ArrayList<String[]> arrayList=ev.listar();
out.println(arrayList.size());
for(String[] strArray : arrayList){
String str="";
for(String str1: strArray)
str=str+" "+str1;
out.println(str);
}
You need to set the attribute in http servlet request and use this in your jsp:
/** Java Controller*/
request.setAttribute("events", lista);
/** JSP */
List<String> events = (List<String>) request.getAttribute("events");