Comparing multiple string value and store them in SET/Array - java

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);
}
}
}

Related

Java Mapping range of IDs to Strings in List

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++;
}

Java - Comparing a single String value with all the String values in an ArrayList

I have an ArrayList with a set of (same) string values which I need to compare with a single String value and return true or false. Is there any way to do
that in Java?
For example, say I have a <String>ArrayList with 5 values = foo, foo, foo, foo, foo (My requirement is such that all the values in the arraylist will be the SAME) and I have a String str = "foo". I need to verify that whether ALL the values in the arraylist is the SAME as the string value i.e., all the values present in the arraylist SHOULD be "foo".
I tried to google this info and all I can see is suggestions to use contains() method, in different ways, which will return true even if anyone value in the arraylist contains the specified value.
I even figured a workaround for this - Creating another arraylist with expected values and compare the two lists using equals() method and it seems
to be working. I was just wondering whether there is any simple way to achieve this.
That's simple with Java 8:
String str = "foo";
List<String> strings = Arrays.asList("foo", "foo", "foo", "foo", "foo");
boolean allMatch = strings.stream().allMatch(s -> s.equals(str));
For Java 7 replace the last line with:
boolean allMatch = true;
for (String string : strings) {
if (!string.equals(str)) {
allMatch = false;
break;
}
}
If you want to know if the array contains the string use ArrayList::contains()
String s = "HI";
ArrayList<String> strings = // here you have your string
if (string.contains(s)) {
// do your stuff
}
If you want to check if all values are same, iterate and count. If you have JAVA8 check steffen sollution.
boolean areSame = true;
for (String str : strings) {
if (!str.equals(s)) areSame = false;
}
if (areSame) {
// all elements are same
}
1) You can the pass the arraylist into a set.
2) Now you can get the size of set, if it is equal to 1 that means all elements are same.
3) Now you can use the contains on set to check if your value is present in it or not.
public static void main(String[] args){
String toBeCompared="foo";
List<String> list=new ArrayList<String>();
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
list.add("foo");
Set<String> set=new HashSet<String>(list);
if(1==set.size()){
System.out.println(set.contains(toBeCompared));
}
else{
System.out.println("List has different values");
}
}
You can use this method to do that
private boolean allAreSame(ArrayList<String> stringList, String compareTo){
for(String s:stringList){
if(!s.equals(compareTo))
return false;
}
return true;
}
I would do it like this:
ArrayList<String> foos = new ArrayList<>();
String str = "foo";
for (String string : foos) {
if(string.equals(str)){
System.out.println("True");
}
}

separating unique values in an algorithm

I am decomposing a series of 90,000+ strings into a discrete list of the individual, non-duplicated pairs of words that are included in the strings with the rxcui id values associated with each string. I have developed a method which tries to accomplish this, but it is producing a lot of redundancy. Analysis of the data shows there are about 12,000 unique words in the 90,000+ source strings, after I clean and format the contents of the strings.
How can I change the code below so that it avoids creating the redundant rows in the destination 2D ArrayList (shown below the code)?
public static ArrayList<ArrayList<String>> getAllWords(String[] tempsArray){//int count = tempsArray.length;
int fieldslenlessthan2 = 0;//ArrayList<String> outputarr = new ArrayList<String>();
ArrayList<ArrayList<String>> twoDimArrayList= new ArrayList<ArrayList<String>>();
int idx = 0;
for (String s : tempsArray) {
String[] fields = s.split("\t");//System.out.println(" --- fields.length is: "+fields.length);
if(fields.length>1){
ArrayList<String> row = new ArrayList<String>();
System.out.println("fields[0] is: "+fields[0]);
String cleanedTerms = cleanTerms(fields[1]);
String[] words = cleanedTerms.split(" ");
for(int j=0;j<words.length;j++){
String word=words[j].trim();
word = word.toLowerCase();
if(isValidWord(word)){//outputarr.add(word);
System.out.println("words["+j+"] is: "+word);
row.add(word_id);//WORD_ID NEEDS TO BE CREATED BY SOME METHOD.
row.add(fields[0]);
row.add(word);
twoDimArrayList.add(row);
idx += 1;
}
}
}else{fieldslenlessthan2 += 1;}
}
System.out.println("........... fieldslenlessthan2 is: "+fieldslenlessthan2);
return twoDimArrayList;
}
The output of the above method currently looks like the following, with many rxcui values for some name values, and with many name values for some rxcui:
How do I change the code above so that the output is a list of unique pairs of name/rxcui values, summarizing all relevant data from the current output while removing only the redundancies?
If you just need a Collection of all words, use a HashSet Sets are primarily used for contains logic. If you need to associate a value with your string use a HashMap
public HashSet<String> getUniqueWords(String[] stringArray) {
HashSet<String> uniqueWords = new HashSet<String>();
for (String str : stringArray) {
uniqueWords.add(str);
}
return uniqueWords;
}
This will give you a collection of all the unique Strings in your array. If you need an ID use a HashMap
String[] strList; // your String array
int idCounter = 0;
HashMap<String, Integer> stringIDMap = new HashMap<String, Integer>();
for (String str : strList) {
if (!stringIDMap.contains(str)) {
stringIDMap.put(str, new Integer(idCounter));
idCounter++;
}
}
This will provide you a HashMap with unique String keys and unique Integer values. To get an id for a String you do this:
stringIDMap.get("myString"); // returns the Integer ID associated with the String "myString"
UPDATE
Based on the question update from the OP. I recommend creating an object that holds the String value and the rxcui. You can then place these in a Set or HashMap using a similar implementation to the one provided above.
public MyObject(String str, int rxcui); // The constructor for your new object
MyObject mo1 = new MyObject("hello", 5);
Either
mySet.add(myObject);
will work or
myMap.put(mo1.getStr, mo1.getRxcui);
What is the purpose of the unique word ID? Is the word itself not unique enough since you are not keeping duplicates?
A very basic way would be to keep a counter going as you are checking new words. For each word that doesn't already exist you could increase the counter and use the new value as the unique id.
Lastly, might I suggest you use a HashMap instead. It would allow you to both insert and retrieve words in O(1) time. I am not entirely sure what you are going for, but I think the HashMap might give you more range.
Edit2:
It would be something a little more along these lines. This should help you out.
public static Set<DataPair> getAllWords(String[] tempsArray) {
Set<DataPair> set = new HashSet<>();
for (String row : tempsArray) {
// PARSE YOUR STRING DATA
// the way you were doing it seemed fine but something like this
String[] rowArray = row.split(" ");
String word = row[1];
int id = Integer.parseInt(row[0]);
DataPair pair = new DataPair(word, id);
set.add(pair);
}
return set;
}
class DataPair {
private String word;
private int id;
public DataPair(String word, int id) {
this.word = word;
this.id = id;
}
public boolean equals(Object o) {
if (o instanceof DataPair) {
return ((DataPair) o).word.equals(word) && ((DataPair) o).id == id;
}
return false;
}
}

Android: Find a value inside an Array with a "a like" value

I'm having problem with this part
My Code:
String[] sample = {'name=NAME', 'add=ADD', 'age=AGE', 'gender=GENDER'};
for(int a = 0; a < sample.length; a++) {
if(Arrays.asList(sample).contains("name")) {
Log.d(tag, "successful");
} else {
Log.d(tag, "failed");
}
}
When I'm using this code, it doesn't return true, but when I use .contains("name=NAME")
it returns true.
Is there any possibility to compare a string value using not too specific string?
BTW, those string values came from a file.txt.
If you use Arrays.asList(sample) you will have a list containing the String "name=NAME" hence it doesn't contain the String "name"
You should loop over the array (not needed to create the list)
boolean found = false;
for (String s: sample)
if (s.contains("name"))
found=true;
To get a value based on key:
1) You can use HashMap object
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Ideone
{
public static void main(String args[]) {
// create hash map
HashMap newmap = new HashMap();
// populate hash map
newmap.put("name", "abcde");
newmap.put("age", "XX");
newmap.put("Gender", "Male");
// get value of key Gender
String val=(String)newmap.get("Gender");
// check the value
System.out.println("Value for key 3 is: " + val);
}
}
2) You can also use Map object
Map<String, String> map = new HashMap<String, String>();
map.put("name", "abcde");
map.put("age", "XX");
String val=(String)map.get("name");
3) You can also use two dimentional array of string
String data = "name=Name,age=Age";
String[] rows = data.split(",");
String[][] matrix = new String[rows.length][];
int r = 0;
for (String row : rows) {
matrix[r++] = row.split("\\=");
}
System.out.println(matrix[1][1]);
.contains method will check whether the object is present in the ArrayList or not.
Here in your case objects are : "name=NAME","add=ADD","age=AGE", "gender=GENDER" which are of String type. So it is obvious that it returns false.
For you, better practice is to create a class named Person which has attributes like name,add,age and gender. Then store the object of it in ArrayList and you can check whether object is in ArrayList of not using .contains() function. Like below :
class Person{
String name;
String add;
int age;
String gen;
// All getters and setters methods will be here.
}
public static void main(String[] args){
Person p = new Person();
//Here you can set the properties of person using p.setXXX() methods
//Now suppose you have ArrayList of Person object named "per" then you can check
// whether Person exist in it or not using contains like below
per.contains(p) //returns true if per contains object p
//or you can check name by below code
for(Person temp:per){
if(temp.getName().equals(name)){ //returns true if name matchs with Persons name
//do something
}
}

For Each Loop to return search string

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()]);
}

Categories