I have the following code that will get me a list of all the country names :D
private List<String> countriesList = new ArrayList<String>();
public List<String> getCountriesList() {
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode);
countriesList.add(obj.getDisplayCountry(Locale.ENGLISH));
}
Collections.sort(countriesList);
countriesList.add(0, "International");
System.out.println(countriesList);
return countriesList;
}
What I need to do is now map all these countries to an ID number.
The ID number will start at: 32000006 and end at 32000260
I am not sure what I need to do to get the numbers mapped.. I know that basically I will pass an int through a method and then that method will match the ID that is passed through to the method and then I need it to return the country name.
I am not sure about how to go about this but one problem I have noticed is that ID 32000008 belongs to the country: Ă…land Islands but as it has a weird A it is at the end of my List. I still need it to have the ID 32000008 though.
If anyone has any idea about what I need to do to my method to finish this off I will be grateful.
Thanks :)
UPDATE
I tried using a HashMap and got this code:
public class test{
public static void main (String[] args) throws java.lang.Exception
{
getCountriesList();
}
private static HashMap<Integer,String> countriesList = new HashMap<Integer,String>();
public static void getCountriesList() {
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
int i = 32000007;
Locale obj = new Locale("", countryCode);
countriesList.put(i,obj.getDisplayCountry(Locale.ENGLISH));
i++;
}
countriesList.put(32000006,"International");
System.out.println(countriesList);
}
}
Which outputs:
{32000006=International, 32000007=Zimbabwe}
Any ideas why it isn't working?
i is a local variable of the loop. So at each iteration, it's reinitialized to 32000007. The variable must be declared out of the loop:
int i = 32000007;
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode);
countriesList.put(i,obj.getDisplayCountry(Locale.ENGLISH));
i++;
}
That said, instead of having a list of strings, and a map of IDs to strings, why don't you create a Country class with two fields: ID and label. Then use a loop to create a List<Country>? That would be much cleaner.
String[] locales = Locale.getISOCountries();
List<Country> countries = new ArrayList<>();
int i = 32000007;
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode);
countries.add(new Country(i, obj.getDisplayCountry(Locale.ENGLISH)));
i++;
}
Related
I want to store the value of string as an array of elements/ or as a set, provided 1 or many string matches. Is it possible to achieve something this this?
Here is the pseudo code
for (String some_string : Name){
IF (some_string.equals("john" OR/AND "mary" OR/AND "peter" OR "etc."){
THEN add them to SET/ Array
}}
public static void test()
{
HashSet<String> set = new HashSet<String>();
set.add("john");
set.add("peter");
set.add("alex");
HashSet<String> newlist = new HashSet<String>();
for (String some_string : Name){
if(set.contains(some_string)){
newlist.add(some_string);
}
}
}
Sorry if the title is not clear, I'm not very good with programming jargon.
I have 2 string ArrayLists and an integer ArrayList obtained from one method which is passed to a separate method through the collection LinkedHashMap< String, List< String>>. However, when I try to set the integer ArrayList into a empty ArrayList declared in the receiving method, it shows the syntax error: "incompatible types: List< String> cannot be converted to List< Integer>".
Starter Method:
public static void main(String[] args) {
try{
LinkedHashMap lhm = new LinkedHashMap();
List<String> listEPC = new ArrayList<String>();
List<String> listTimeStamp = new ArrayList<String>();
List<Integer> listAntenna = new ArrayList<Integer>();
String tagID = "EQ5237";
String TimeStampStr = "12:23:22";
int tagAntenna = 2;
listEPC.add(tagID);
listTimeStamp.add(TimeStampStr);
listAntenna.add(tagAntenna);
lhm.put("epcs", listEPC);
lhm.put("timestamps", listTimeStamp);
lhm.put("antennas", listAntenna);
insertData insert = new insertData();
insert.insertData(lhm); //send map with values to new method
}catch(Exception e){
e.printStackTrace();
}
}
Receiving Method:
public class insertData {
public void insertData(LinkedHashMap<String, List<String>> readMap) {
List<String> listEPC = new ArrayList<String>();
List<String> listTimeStamp = new ArrayList<String>();
List<Integer> listAntenna = new ArrayList<Integer>();
String EPC = null;
String TimeStamp = null;
Integer Antenna = null;
listEPC = readMap.get("epcs");
listTimeStamp = readMap.get("timestamps");
listAntenna = readMap.get("antennas"); //error message here
for(int i=0; i<readMap.size(); i++){
EPC = listEPC.get(i);
TimeStamp = listTimeStamp.get(i);
Antenna = listAntenna.get(i);
System.out.println("Entry " + i );
System.out.println("Values: " + EPC + TimeStamp + Antenna);
}
}
}
This code works only if I change all instances of integers to strings, which is not what I would like in my actual code. Why is it so and how do I work around it?
You can't assign a List<String> to a List<Integer>. The elements are fundamentally different types.
You would need to construct a new List:
List<Integer> listOfIntegers = new ArrayList<>();
for (String entry : listOfStrings) {
listOfIntegers.add(Integer.valueOf(entry);
}
Of course, you also need to handle the possibility that elements of the list cannot be parsed as integers.
However, you are just throwing away type information by stuffing everything into a single map. It would be better to pass the three lists separately:
insertData(listEPC, listTimestamp, listAntenna);
and then you can have different list types in the method signature:
void insertData(
List<String> listEPC,
List<String> listTimestamp,
List<Integer> listAntenna) { ... }
I am going to include the proper answer at the bottom, but in regards to your question title, you'll have to change your method signature to:
LinkedHashmap<String, List<?>> readMap;
Then either cast the lists, which will cause an unsafe cast. eg.
List<String> listEPC = (List<String>)readMap.get("epcs");
Or cast the object.
List<?> listEPC = readMap.get("epcs");
Then in the loop cast.
EPC = (String)listEPC.get(i);
Note, these are not good solutions.
What you should have is one List that contains an object with all of the data's you need.
I can imagine the thought process went something along these lines, "I have these things, and they contain two strings and an integer. I will create a variable for each." Then you ask the question, "How do I create a collection of these things?"
The wrong answer to this question is, "I will make a list for each value, and match associated values by index." The correct answer is, "I will create a class to represent my data, and store that in a list." This is the basic essence of object orient programming (welcome to java).
First we design the class:
class EPCThing{
String EPC;
String timeStamp;
int Antennas;
public EPCThing(String tagId, String timeStamp, int antennas){
EPC=tagId;
this.timeStamp = timeStamp;
Antennas = antennas;
}
#Override
public String toString(){
return "Values: " + EPC + TimeStamp + Antenna
}
}
Now your program's main method will be something like.
List<EPCThing> things = new ArrayList<>();
String tagID = "EQ5237";
String TimeStampStr = "12:23:22";
int tagAntenna = 2;
EPCThing thing = new EPCThing(tagID, TimeStampStr, tagAntenna);
things.add(thing);
insertData insert = new insertData();
insert.insertData(things);
Then we can fix your insertData method
public void insertData(List<EPCThing> things) {
for(int i=0; i<things.size(); i++){
System.out.println("Entry " + i );
System.out.println("Values: " + things.get(i));
}
}
I am trying to find all of the name of countries.
I tried to get them from java.util.Locale but I found that there is some countries with wrong names and the list is not alphabetically arranged.
to get the list from java.util.Locale I used this code
private List<String> countriesList = new ArrayList<String>();
public List<String> getCountriesList() {
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode);
countriesList.add(obj.getDisplayCountry(Locale.FRENCH));
}
return countriesList;
}
So is there a way to make them alphabetically arranged with the correct names ?
Just use Collections.sort(listName) and your list will get sorted
List<String> countriesList = new ArrayList<String>();
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode);
countriesList.add(obj.getDisplayCountry(Locale.FRENCH));
Collections.sort(countriesList);
}
for(String s:countriesList)
{
System.out.println(s);
}
In your code just add sort method before the return statement of the method
private List<String> countriesList = new ArrayList<String>();
public List<String> getCountriesList() {
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode);
countriesList.add(obj.getDisplayCountry(Locale.FRENCH));
}
Collections.sort(countriesList);
return countriesList;
}
I think there are two separate issues:
The list is not alphabetically arranged.
You just need to sort the array. There are numerous ways how to do it, one of them could be as follows:
Collections.sort(countriesList, new Comparator<String>() {
#Override
public int compare(String str1, String Str2)
{
return str1.compareTo(str2);
}
});
Some countries with wrong names
If there are countries with wrong names, particularly in your language, it will be hard to do anything with it within Java. If you cannot rely on the internal Java country names, you could either put the name list directly into your application "manually", which could be annoying or e.g. use a web service. There are many, check e.g. this one. The advantage of this approach is that the list may be updated if some new countries appears, what happens time to time.
Consider I have an Arraylist which holds products name like
Dell Inspiron Laptop
Apple iPad
Samsung S4
I want to have a search like if one searches for S4, it returns Samsung S4. I tried to find the answer in many websites but didn't get one. I used .matches and .contains but was of no use.
Iterate the product names list, assume the variable for product name is name, which is a String type.
You can use if (name.contains(value)) { or if(name.indexOf(value)!=-1){ to check whether the name contains the value to be searched.
Have a try with the following code:
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> prodNames = new ArrayList<String>();
prodNames.add("Dell Inspiron Laptop");
prodNames.add("Apple iPad");
prodNames.add("Samsung S4");
// Search S4 and it will print Samsung S4 in Console
System.out.println(search("S4", prodNames));
}
public static String search(String value, List<String> prodNames) {
for (String name : prodNames) {
if (name.contains(value)) {
return name;
}
}
return null;
}
}
You can write an utility function like below, that scans through contents of list for particular pattern. Hope this works for your.
public static void findMatch(List<String> listNames, String searchTerm){
for(String inName:listNames){
if(inName!=null)
if(inName.contains(searchTerm))
System.out.println(" Match Found for "+inName);
}
}
You could do something like:
public List<String> matches (List<String> dataList, String matchStr){
List<String> result = new ArrayList<String>();
if (matchStr != null) {
matchStr = matchStr.toLowerCase();
for(String d : dataList){
if (d.toLowerCase().contains(matchStr)) {
result.add(d);
}
}
}
return result;
}
First of all clean up the definition of the Array. I'm guessing that it actually looks like this:
{ "Dell Inspiron", "Apple iPad", "Samsung S4" }
Then go run this in your IDE :
import java.util.ArrayList;
import java.util.List;
class TestSearching {
public static void main(String args[]) {
List<String> products = new ArrayList<String>();
products.add("Dell Inspiron");
products.add("Apple iPad");
products.add("Samsung S4");
System.out.println("Matches to S4 : " + findMatches(products,"S4"));
}
public static List<String> findMatches(List<String> products, String searchTerm) {
List<String> result = new ArrayList<String>();
for (String product : products) {
if ( product.contains(searchTerm) ) result.add(product);
}
return result;
}
}
If you always want to do a lookup on the string after the first space, then maybe you don't want to use an ArrayList
Maybe you should use a Map<String, String> of product, full name e.g. "S4", "Samsung S4"
Then lookups will be much faster.
I'm having trouble with my JAVA command line menu. Here's what I've got.. what I want to do is in the comments.
private void listStudents(){
out.println("\n\tStudent Listing");
//Call datastore method that returns all student names as an array of strings
String[] list = data.getStudents();
//Display all names (use foreach statement)
for (String name : list) {
}
}
here's the data store method I'm also stuck with...
String[] getStudents() {
return (String[]) students.toArray();
}
// Method to return students who match search term
String[] findStudents(String searchTerms) {
// Use foreach loop to visit each item in students ArrayList,
// and if the name matches the search term, add it to a new ArraList.
// Then return the new ArrayList as a string array (see getStudents)
}
Not sure if this is exactly what you need, but based on what I understood from your comments, try using the following:
private void listStudents()
{
System.out.println("\n\tStudent Listing");
String[] list = data.getStudents();
// List each student.
for (String name : list)
System.out.println(name);
}
private String[] findStudents(String searchTerms)
{
List<String> studentsFound = new ArrayList<String>();
for (String student : students)
{
// Determine if matching student found.
if (student.equals(searchTerms))
studentsFound.add(student);
}
return studentsFound.toArray(new String[0]);
}
You've not defined what the searchterms might. Is it a regular expression? Is it a wildcard?
public String[] findStudents(String searchTerms) {
List<String> findList = new ArrayList<String>(25);
for (String student : students) {
// Now you'll need to define how the match works,
// Are you using a regexp or some kind of other matching
// algorithm..
boolean match = ...;
if (match) {
findList.add(student);
}
}
return findList.toArray(new String[findList.size()]);
}