How to get random string value without duplicate? - java

I want to fetch only a single company name and I want to fetch it only once. So if it already was fetched, it should not be fetched again.
Here is the code:
private static String[] billercompanies = {
"1st",
"TELUS Communications",
"Rogers Cablesystems",
"Shaw Cable",
"TELUS Mobility Inc",
"Nanaimo Regional District of",
"Credit Union MasterCard",
};
public static String GetBillerCompany(){
String randomBillerComp = "";
randomBillerComp = (billercompanies[new Random().nextInt(billercompanies.length)]);
return randomBillerComp;
}

Just shuffle the array you want using Collections
Collections.shuffle(List);
So simply create a list from your array
List<E> list = Arrays.asList(array);
Then shuffle it using the method above
Collections.shuffle(list);
Your list can be read from left to right as it was random.
So simply save the index
int currentIndex = 0;
public E getRandom(){
//If at the end, start over
if(++currentIndex == list.size()) {
currentIndex = 0;
shuffle(list);
}
return list.get(currentIndex);
}
Each time you want to forget the duplicate list you already used, simply shuffle the array again
Collections.shuffle(list);
Without index
You could simply remove the first value each time, once the list is empty, recreate it with the original array. As Ole V.V. pointer out, a List generated by Arrays.asList(E[]) doesn't support the remove methods so it is necessary to generate a new instance from it.
Here is a quick and simple class using this solution :
public class RandomList<E>{
E[] array;
List<E> list;
public RandomList(E[] array){
this.array = array;
buildList(array);
}
public E getRandom(){
if(list.isEmpty()) buildList(array);
return list.remove(0);
}
public void buildList(E[] array){
list = new ArrayList<E>(Arrays.asList(array));
Collections.shuffle(list);
}
}
And the test was done with this small code :
Integer[] array = {1,2,3,4,5};
RandomList<Integer> rl = new RandomList(array);
int i = 0;
while(i++ < 10)
System.out.println(rl.getRandom());

Make a copy in a List and remove the element when it was already fetched.
Arrays.asList(array) is not modifiable but you can wrap it in a full featured List.
List<String> billercompaniesList = new ArrayList<>(Arrays.asList(billercompanies));
String randomBillerComp = "";
Random random = new Random();
// first retrieval
int index = random.nextInt(billercompaniesList.size());
randomBillerComp = billercompaniesList.get(index);
billercompaniesList.remove(index);
// second retrieval
index = random.nextInt(billercompaniesList.size());
randomBillerComp = billercompaniesList.get(index);
billercompaniesList.remove(index);
// and so for

Related

why is everything getting removed from my arraylist?

I'm trying to answer this question:
Program the method findIngredients. This method takes in a String called
foodInStock, and an ArrayList of Strings called ingredients. The method should return an
ArrayList of ingredients that were not found in foodInStock.
for example if:
foodInStock = “tomatopotatocornturkeycarrotstuffing”
ingredients = {“potato”, “corn”, “salt”, “chicken”, “turkey”}
returns {“salt”, “chicken”}
I tried writing some code but for some reason everything is getting removed when I use the above example on my program. Where did my program go wrong?
Here's my code:
public static ArrayList<String> findIngredients(String foodInStock, ArrayList<String> ingredients){
ArrayList<String> ingredientsNotFound = new ArrayList<String>();
int i = 0;
for (; i < ingredients.size(); i++) {
for (int x = 0; x < foodInStock.length()-(ingredients.get(i).length())+1; x++) {
if (ingredients.get(i) == foodInStock.substring(x, (x + ingredients.get(i).length()))) {
ingredients.remove(i);
i = 0;
break;
}
}
}
ingredients = ingredientsNotFound;
return ingredientsNotFound;
}
I think there are two main things to cover here.
First, the way to build the final result. You are currently removing items from the original input; a better strategy is to add items to a new list (partially because it's simpler to think about and partially because you generally don't want to modify a list while iterating over it).
You also are, probably accidentally, overwriting your list with an empty list at the end.
Second, the way to determine whether or not the ingredient is in the string input. Rather than looping over the whole string and inspecting substrings, you can instead use the indexOf() method to see whether or not the string includes the current item.
public static ArrayList<String> findIngredients(String foodInStock, ArrayList<String> ingredients) {
ArrayList<String> results = new ArrayList<>();
for (String ingredient : ingredients) {
if (foodInStock.indexOf(ingredient) == -1) {
results.add(ingredient);
}
}
return results;
}
Here we initialize a new list for the results. We then loop over every individual ingredient in the input list, and ask whether or not that ingredient is present in the string input. When it is not (indexOf() returns -1), we add it to the results list. At the end, the results contains every ingredient not found.

Update element in Arraylist java

Sorry to repeat the question but i am new and looking the others answers didn't help me much.
I'd like to update my arraylist but i get stuck in an error that i cannot solve. Eclipse underlines the word set.
My code is:
private List<List> lists;
public void updateList(int index, string a) throws listException {
for(index = 0; index<list.size(); index++) {
list.get(index);
list.set(index, a);
}
You named the list as lists and trying to access list in the for-loop.
So your for loop should become like this:
for(index = 0; index<lists.size(); index++) {
lists.get(index);
lists.set(index, a);
}
Also it's String and not string and you will have to initialize the list.
So first change:
// Type should be String
private List<String> lists = new ArrayList<>();
And am not sure what is listException.
public void updateList(int index, String a) {
// Your rest of the code.

Java: find Id By Title () from models

This is my function, to find a id from list by matching titles
public static int findIdByTitle(List<Integer> IDs, List<String> Titles ,String title){
for (int i = 0; i < IDs.size(); i++){
if (Titles.get(i).equals(title))
return IDs.get(i);
}
return 0;
}
This function search in model list and find id
But I can't use this because:
int id = findIdByTitle(Core.userSignIn.getBasicList().getGradeList().get(****?****).getID()
,Core.userSignIn.getBasicList().getGradeList().get(****?****).getName()
,spinnerGrade.getSelectedItem().toString());
I must give it a number position : ( see the lists.get(****?****).getID() or getName()
I want using that's function for all models not just for this model
give 2 lists and a matching word, use matching word to find position of that's in list, and give me a ID of this position
All of my model have ID , Title and some of them have ParentID
with help of Nitin , My problem has been resolved:
List<String> Titles = new ArrayList<>();
List<Integer> IDs = new ArrayList<>();
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.N) {
Titles = Core.userSignIn.getBasicList().getGradeList().stream().map(GradeList::getGradeName).collect(Collectors.toList());
IDs = Core.userSignIn.getBasicList().getGradeList().stream().map(GradeList::getGradeID).collect(Collectors.toList());
} else {
Titles = new ArrayList<>(Core.userSignIn.getBasicList().getGradeList().size());
IDs = new ArrayList<>(Core.userSignIn.getBasicList().getGradeList().size());
for (GradeList gradeList : Core.userSignIn.getBasicList().getGradeList()) {
Titles.add(gradeList.getGradeName());
IDs.add(gradeList.getGradeID());
}
}
educationList1.setiGradeID(findIdByTitle(IDs
,Titles
,spGrade.getSelectedItem().toString()));
You first have to convert your list to List of Integer and List of String and then pass it to your method. You can use below code if you are using Java 8:
final List<Integer> testList1 = BasicList().getGradeList().stream().map(Test::getId).collect(Collectors.toList());
final List<String> testList2 = BasicList().getGradeList().stream().map(Test::getName).collect(Collectors.toList());
Replace your class name in place of Test in above code.
Use below code for below java 8 env:
List<String> strings = new ArrayList<>(BasicList().getGradeList().size());
for (Test test : BasicList().getGradeList()) {
strings.add(test.getName());
}
Similar for Ids.
You need another loop if you want to get all Ids of your models, you can do something like this :
List<Integer> listId=new ArrayList<Integer>();
for(int i=0; i<BasicList().getGradeList().size(); i++) {
listId.add(findIdByTitle(BasicList().getGradeList().get(i).getID()
,BasicList().getGradeList().get(i).getName()
,spinnerGrade.getSelectedItem().toString()));
}

How to return multiple values within a search function(array) in Java

I have a search function in a class that searches through an array by a String(Department of work) and a count.
In the main the program will ask the user what category does he/she wants to search for. Example: library ; the program should give all the books that are in that specific department (there is a function that lets the user add books)
The problem is that the program only returns one book and not the all the books that are associated within that Category.
Your function should not return an single index it should return a collection of indexes.
For example.
public static Collection<Integers> Searchdep(EmployeeClass EmployeeArr[], String department, int size) {
List<Integer> intList = new ArrayList<Integer>();
for(int i=0; i<size; i++)
{
if(EmployeeArr[i].Department.equals(department)) {
intList.add(i);
}
}
return intList;
}
Then in your main check for size of the collection, if it is zero that mean nothing was found.
Theses the line need to change
index=EmployeeClass.SearchDep(EmpList,department,count);
JOptionPane.showMessageDialog(null,index);
to
Collection<Integer> returnedCollection = EmployeeClass.SearchDep(EmpList,department,count);
if(returnedCollection.isEmpty()){
JOptionPane.showMessageDialog(null,"Nothing was found");
} else {
StringBuilder str = new StringBuilder();
for(Integer integer: returnedCollection){
str.appened(EmpList[integer].ReturnStringInfo());
str.appened(", ");
}
JOptionPane.showMessageDialog(null,"Indexed are : "+ str.toString());
}
Just return an array of indices instead of a single index. For example:
public static List<Integer> Searchdep(EmployeeClass EmployeeArr[], String department, int size){
List<Integer> result = new ArrayList<Integer>();
for(int i=0; i<size; i++){
if(EmployeeArr[i].Department.equals(department)){
result.add(i);
}
}
return result;
}
The best option here is to pass a Visitor action to apply to each employee found. In Java 8, this would be a lambda but in Java 6 or 7 this would be an anonymous inner class.
Then you might return the count found so you can detect when there was no matches.

Re-order ArrayList Based on String Array's Order - Java

I have one arraylist and one String array. The String array contains IDs and the Array List contains the ids and information related to those Ids. This ArrayList is in an undesirable order. I have a String Array of the Ids in the order in which I want them to be in the ArrayList.
Semi-Pseudocode Example:
ArrayList<MyObject> myList = new ArrayList<MyObject>();
for (every username)
{
myList.add(new MyObject(id, username, content, country);
}
String[] ids = new String[myList.size()];
...Ids are added and sorted here...
I now have a list of Ids, in their correct order. Each Id in "myList" corresponds to an Id in the "ids" String Array. I want to sort "myList" based on the order of it's corresponding id in the "ids" String Array.
How can I re-sort my ArrayList in such a way?
Eg. if in Array list I have:
1. 123, Bob, test, USA
2. 1234, Vladimir, test, USA
3. 12345, Yoseph, test, USA
and in the String[] I have:
1. 1234
2. 123
3.12345
How can I reorder the ArrayList based off of the Ids in the String Array, thus producing:
1. 1234, Vladimir, test, USA
2. 123, Bob, test, USA
3. 12345, Yoseph, test, USA
One solution would be to iterate over the ids array, and search the object for the current id in the array. We know its final (desired) position: it is the index in the array (because we want the list sorted just like the array), so we can move this element to its final place in the list (we do this by swapping it with the element being at the position we're at currently in the array).
for (int i = ids.length - 1; i > 0; i--) { // Downward for efficiency
final String id = ids[i];
// Big optimization: we don't have to search the full list as the part
// before i is already sorted and object for id can only be on the remaining
for (int j = i; j >= 0; j--) // NOTE: loop starting at i
if (id.equals(myList.get(j).getId()) {
Collections.swap(myList, j, i);
break;
}
}
Note: the for loop omits the last element (i==0) because if all other elements are in place, the last is also in (its) place.
This is much faster than creating a comparator and using a sorting algorithm (which Collections.sort() does for example) because the order of the elements is already known (defined by the ids array) and sorting algorithms (no matter how smart the algorithms are) can only use the info [less | equals | greater] returned by comparators.
You could write your own Comparator based on the index in the array:
public class MyObjectComparator implements Comparator<MyObject> {
private List<String> ids;
public MyObjectComparator(String[] ids) {
this.ids = Arrays.asList(ids); // Copying the array would be safer
}
public int compare (MyObject obj1, MyObject obj2) {
return Integer.compare(ids.indexOf(obj1), ids.indexOf(obj2));
}
}
// Use it:
Collections.sort (myList, new MyObjectComparator(ids));
You simply need a comparator:
List<String> ids = Arrays.asList(array);
Collections.sort(list, new Comparator<MyObject>() {
#Override
public int compare(MyObject o1, MyObject o2) {
return Integer.compare(ids.indexOf(o1.getId()), ids.indexOf(o2.getId()));
}
});
Of course, if your list is large, this will be very inefficient. So you'd better build a Map<String, Integer> containing each ID as key and its position in the array as value, and use this map inside the comparator:
Map<String, Integer> idPositions = new HashMap<>();
for (int i = 0; i < array.length; i++) {
idPositions.put(array[i], i);
}
Collections.sort(list, new Comparator<MyObject>() {
#Override
public int compare(MyObject o1, MyObject o2) {
return idPositions.get(o1.getId()).compareTo(idPositions.get(o2.getId()));
}
});
crs_rawStepSeqNum: Your arrayList
crs_rawStepSeqNum: Same arrayList
for(int x =0;x<crs_rawStepSeqNum.size();x++)
if((x+1) < crs_rawStepSeqNum.size()) {
if (Integer.parseInt(crs_rawStepSeqNum.get(x)) > Integer.parseInt(crs_rawStepSeqNum.get(x + 1))) {
crs_rawStepSeqNum.set(x, crs_rawStepSeqNum.get(x + 1));
crs_rawStepSeqNum.set(x + 1, crs_StepSeqNum.get(x));
crs_StepSeqNum.clear();
crs_StepSeqNum.addAll(crs_rawStepSeqNum);
x=0;
}
}
}

Categories

Resources