Here i'm able to get User Screen names and printing with the below code,but how can i sort those name alphabatically.
Twitter twitter = (Twitter) request.getSession().getAttribute("twitter");
String name = (String) request.getSession().getAttribute("name");
long cursor = -1;
IDs ids = twitter.getFollowersIDs(name, cursor);
do {
for (long id : ids.getIDs()) {
User user = twitter.showUser(id);
out.println(user.getName());
}
} while ((cursor = ids.getNextCursor()) != 0);
This is my code where i'm getting names,how can i sort names.Thank for your help.
Actually a Comparator may be more than you need, I got mixed up with your previous question.
You can simply collect the names themselves in a list and then sort, e.g.:
...
final List<String> names = new LinkedList<String>();
do {
for (...) {
...
names.add(user.getName());
}
} while (...);
Collections.sort(names)
If you inspect names, it will now be sorted.
Related
I'm trying to concatenate 2 array lists of objects into one but i can't figure out how to do it. I've tried with addAll and add but those methods won't really do what i want.
Basically, i have one array list with values like this:
SearchResult1 [title=null, url=null, price=19 690 EUR]
And another one with values like this:
SearchResult2 [title=Ford Car, url=http://www.something.com, price=null]
How can i combine those 2 arrays into one with values like this:
SearchResult3 [title=Ford Car, url=http://www.something.com, price=19 690 EUR]
This is the code so far:
public List searchMethod() {
try {
final String query = "ford";
final Document page = Jsoup.connect("link" + URLEncoder.encode(query, "UTF-8")).userAgent(USER_AGENT).get();
List<SearchResult> resultList1 = new ArrayList<SearchResult>();
List<SearchResult> resultList2 = new ArrayList<SearchResult>();
List<SearchResult> resultList3 = new ArrayList<SearchResult>();
for(Element searchResult : page.select(".offer-price")) {
String price = searchResult.text();
resultList1.add(new SearchResult(price));
}
for(Element searchResult : page.select(".offer-title__link")) {
String title = searchResult.text();
String url = searchResult.attr("href");
resultList2.add(new SearchResult(title, url));
}
resultList3.addAll(resultList1);
resultList3.addAll(resultList2);
return resultList3;
}catch(Exception e) {
e.printStackTrace();
}
return Collections.emptyList();
}
The values that i put in those arrays are extracted from a web page
Thanks for helping!
From the comment, you have said that you just want to correlate/merge the objects from both lists by each index.
You can simply loop through the list, constructing a new SearchResult (assuming you have getters for the fields)
for(int i = 0; i < resultList1.size(); i++) {
resultList3.add(new SearchResult(resultList1.get(i).getPrice(),
resultList2.get(i).getTitle(),
resultList2.get(i).getUrl()));
}
You may have to change the order of the passed arguments to the SearchResult constructor taking price, title and url as you haven't shown it.
why don't you do it in one shot?
List<SearchResult> resultList1 = new ArrayList<SearchResult>();
for(Element searchResult : page.select(".offer-title__link")) {
String title = searchResult.text();
String url = searchResult.attr("href");
resultList1.add(new SearchResult(title, url));
}
int index = 0;
for(Element searchResult : page.select(".offer-price")) {
String price = searchResult.text();
//since you have already assumed
//that price will come in the same order and title and url.
resultList1.get(index++).setPrice(price);
}
return resultList1;
My question is when i store the data into array from sqlite database, how can i get it from specific position let say, my database contain "food, drinks,snack" how can i get the string "snack" from array.
String CatNameQuery = "SELECT * FROM Category";
db = new DBController(MainActivity.this);
SQLiteDatabase db3 = db.getReadableDatabase();
final Cursor cursor2 = db3.rawQuery(CatNameQuery, null);
{
List<String> array = new ArrayList<String>();
while(cursor2.moveToNext()){
String uname = cursor2.getString(cursor2.getColumnIndex("CategoryName"));
array.add(uname);
}
You need to iterate through the list in order to find the item you are looking for.
For example:
for (String s : array) {
if (s.equals("snack")) {
System.out.println("Found snack");
}
}
You can also use the contains method to check if the list contains "snack."
if (array.contains("snack")) {
System.out.println("Found snack");
}
Resource: ArrayList
Use the WHERE clause within your SELECT query. For example:
"SELECT * FROM Category WHERE CategoryName='snacks'"
This will fill your array with only items under the category 'snacks'.
List<String> array = new ArrayList<String>();
array.add("food");
array.add("drinks");
array.add("snack");
String result="";
if (array.contains("snack")) // avoid null pointer exception
{
int index =array.indexOf("snack") //find the index of arraylist
result=array.get(index);
}
You can find it by looping the array
List<String> arrobj= new ArrayList<String>();
arrobj.add("food");
arrobj.add("drinks");
arrobj.add("snack");
for (String value : arrobj) {
if (value.equals("snack")) {
System.out.println("Here is the snack");
}
}
if (array.size() > 0) {
int index = 0;
if (array.contains("Snacks")) {
index = array.indexOf("Snacks");
System.out.println(array.get(index));
}
}
I am trying to retrieve and process code from JIRA, unfortunately the pieces of information (which are in the Metadata-Plugin) are saved in a column, not a row.
Picture of JIRA-MySQL-Database
The goal is to save this in an object with following attributes:
public class DesiredObject {
private String Object_Key;
private String Aze.kunde.name;
private Long Aze.kunde.schluessel;
private String Aze.projekt.name;
private Long Aze.projekt.schluessel
//getters and setters here
}
My workbench is STS and it's a Spring-Boot-Application.
I can fetch a List of Object-Keys with the JRJC using:
JiraController jiraconnect = new JiraController();
List<JiraProject> jiraprojects = new ArrayList<JiraProject>();
jiraprojects = jiraconnect.findJiraProjects();
This is perfectly working, also the USER_KEY and USER_VALUE are easily retrievable, but I hope there is a better way than to perform
three SQL-Searches for each project and then somehow build an object from all those lists.
I was starting with
for (JiraProject jp : jiraprojects) {
String SQL = "select * from jira_metadata where ENRICHED_OBJECT_KEY = ?";
List<DesiredObject> do = jdbcTemplateObject.query(SQL, new Object[] { "com.atlassian.jira.project.Project:" + jp.getProjectkey() }, XXX);
}
to get a list with every object, but I'm stuck as i can't figure out a ObjectMapper (XXX) who is able to write this into an object.
Usually I go with
object.setter(rs.getString("SQL-Column"));
But that isn't working, as all my columns are called the same. (USER_KEY & USER_VALUE)
The Database is automatically created by JIRA, so I can't "fix" it.
The Object_Keys are unique which is why I tried to use those to collect all the data from my SQL-Table.
I hope all you need to enlighten me is in this post, if not feel free to ask for more!
Edit: Don't worry if there are some 'project' and 'projekt', that's because I gave most of my classes german names and descriptions..
I created a Hashmap with the Objectkey and an unique token in brackets, e.g.: "(1)JIRA".
String SQL = "select * from ao_cc6aeb_jira_metadata";
List<JiraImportObjekt> jioList = jdbcTemplateObject.query(SQL, new JiraImportObjektMapper());
HashMap<String, String> hmap = new HashMap<String, String>();
Integer unique = 1;
for (JiraImportObjekt jio : jioList) {
hmap.put("(" + unique.toString() + ")" + jio.getEnriched_Object_Key(),
jio.getUser_Key() + "(" + jio.getUser_Value() + ")");
unique++;
}
I changed this into a TreeMap
Map<String, String> tmap = new TreeMap<String, String>(hmap);
And then i iterated through that treemap via
String aktuProj = new String();
for (String s : tmap.keySet()) {
if (aktuProj.equals(s.replaceAll("\\([^\\(]*\\)", ""))) {
} else { //Add Element to list and start new Element }
//a lot of other stuff
}
What I did was to put all the data in the right order, iterate through and process everything like I wanted it.
Object hinfo = hmap.get(s);
if (hinfo.toString().replaceAll("\\([^\\(]*\\)", "").equals("aze.kunde.schluessel")) {
Matcher m = Pattern.compile("\\(([^)]+)\\)").matcher(hinfo.toString());
while (m.find()) {
jmo[obj].setAzeKundeSchluessel(Long.parseLong(m.group(1), 10));
// logger.info("AzeKundeSchluessel: " +
// jmo[obj].getAzeKundeSchluessel());
}
} else ...
After the loop I needed to add the last Element.
Now I have a List with the Elements which is easy to use and ready for further steps.
I cut out a lot of code because most of it is customized for my problem.. the roadmap should be enough to solve it though.
Good luck!
I have an ArrayList of custom made Users. The list is already sorted by manager.My goal is to go through the list by manager and add each user to the body of an email depending on their expiration date.
A User is basically built like this from the database. All necessary accessors/mutators are present:
id|fName|lName|...|manager
Go through the users and notify the manager if the user is expiring:
To: Manager
Expiring in 10 days
<User>
<User>
Expiring in 30 days
<User>
StringBuilder body = new StringBuilder();
ArrayList<Users> contractors;
Date today = cal.getTime();
...
if(contractors != null && contractors.size() > 0){
for(int i = 0; i < contractors.size(); i++){
if(i+1 > contractors.size()){
//do something to avoid outOfBounds and still access last item in the list
}else{
if (contractors.get(i+1).getManager() != null){
if(manager.equals(contractors.get(i+1).getManager())){
if(today.compareTo(contractor.getExpiration()){
//build body of email
}
}
}
sendEmail(manager, body.toString());
}else{
//new manager
body.equals(""); // reset email for next run
}
}
After the email is sent I want to move on to the next set of users based on manager. My problem is that I'm having trouble with the logic behind traversing the array by manager and then resetting everytime for each new manager. I'm thinking that I need another for loop?
What's the best way to do this? thanks
Edit
When implemented this way:
I would do it something like this:
if (contractors != null) {
String currentManager = null;
for (User contractor : contractors) {
String contractorManager = contractor.getManager();
if (!contractorManager.equals(currentManager) {
// a new manager
if (currentManager != null) {
sendEmail(body.toString());
body.setLength(0);
}
currentManager = contractorManager;
}
//build body of email ...
}
// send the email for the last manager
sendEmail(body.toString());
}
Iterate the list of Users and add them to a Map keyed by manager with a Set of employees per manager. Something like,
if (contractors != null && contractors.size() > 0) {
Map<String, Set<Users>> map = new HashMap<>();
for (Users contractor : contractors) {
String manager = contractor.getManager();
if (manager == null) {
manager = contractor.getName();
}
Set<Users> employees = map.get(manager);
if (employees == null) {
employees = new HashSet<>();
map.put(manager, employees);
}
employees.add(contractor);
} // now you can iterate the keySet and then each manager's employees like
for (String manager : map.keySet()) {
Set<Users> employees = map.get(manager);
for (Users u : employees) {
// ...
}
}
}
You should go for a "foreach" loop on contractors, more info here
another example here
If they are already sorted, you can take this approach (I'm using "ManagerObject" to represent the return type of Users.getManager() - replace with the actual class name):
StringBuilder body = new StringBuilder();
ManagerObject currentManager = null;
for (Users contractor : contractors) {
if (currentManager != null && !(contractor.getManager().equals(currentManager)) {
sendEmail(body.toString());
body.equals("");
}
currentManager = contractor.getManager();
// Add stuff to the body for this contractor
}
If the call to Users.getManager() is computationally expensive for some reason, this can be rejiggered to only set the currentManager upon a change in value
I have TreeMap using the Joda DateTime object and is does not seem to be sorting here is the definition:
TreeMap<DateTime, HolderAnswer> dateTimeTreeMap = new TreeMap<DateTime, HolderAnswer>();
I added in the values as follows (I'm just using a generic sql statement here);
//then get previously selected answers to move to the top of the list
String sql = "Select ActionDT, RecID, TextID, Text, Value from Foo";
Cursor c = DataBaseConnector.query(sql);
if (c != null) {
if (c.moveToFirst()) {
do {
HolderAnswer answer = null;
boolean valueAlreadyIn = false;
DateTime dt = formatter.parseDateTime(c.getString(c.getColumnIndex("ActionDT")));
//we will be adding in the options in the next section, setting to null for now.
answer = new HolderAnswer(c.getInt(c.getColumnIndex("RecID")),c.getInt(c.getColumnIndex("TextID")),null,count,c.getString(c.getColumnIndex("Text")));
//////////////////////////////////////////////////////////////
Iterator<Entry<DateTime, HolderAnswer>> it = dateTimeTreeMap.entrySet().iterator();
while (it.hasNext()) {
Entry<DateTime, HolderAnswer> pairs = it.next();
HolderAnswer tempAnswer = (HolderAnswer) pairs.getValue();
DateTime tempDateTime = (DateTime) pairs.getKey();
//if answers match, transfer over options
if (answer.getTextID() == tempAnswer.getTextID()) {
valueAlreadyIn = true;
}
}
if (!valueAlreadyIn) {
dateTimeTreeMap.put(dt,answer);
}
//////////////////////////////////////////////////////////////////
//count++;
} while(c.moveToNext());
c.close();
c = null;
}
}
When I print out the values, they don't seem to be sorted, they come out in no discernable pattern. Even doing:
dateTimeTreeMap.descendingMap();
Does nothing. Am I missing something?
The descendingMap() method is used to return a reverse order view of the mappings contained in this map so it looks like you're forgetting to assign the sorted map to the original one.
dateTimeTreeMap = dateTimeTreeMap.descendingMap();