So lets say I want to make an array of nine country names. I have the code to create the array:
String[] countryName = new String[9];
Lets say I wanted to add nine unique country names to this array. I could do something like this:
countryName[0] = "Mexico";
countryName[1] = "United States";
and so on. But is there a way I could add all of the names at once? Maybe something like an add() statement?
you can initialize the array with:
String[] countryName = new String[]{"Mexico", "Italy", "Spain"};
You can write simple utility method using varargs
static void addAll(String[] arr, String ... elements)
{
if (elements != null)
{
System.arraycopy(elements, 0, arr, 0, elements.length);
}
}
Usage
addAll(countryName, "Mexico", "US", "Ukraine");
Use an ArrayList this has the Add method.
ArrayList<String> countryName = new ArrayList<String>();
countryName.add("Mexico");
countryName.add("United States");
countryName.add("Dominican Republic");
countryName.add("...");
Enlist all contries in String and use split
String str="Country1,Country2,Country3";
String array[]=str.split(",");//You even don't need to initialize array
Use delimeter carefully to avoid extra spaces.
NOTE:
As this is one of the ways to add values to array but still I suggest you to go for Michel Foucault's answer as split will have more overhead than direct initialization.
Related
I'm have defined a list like the below
List<String> list = List.of("val1", "val2", "val3");
Now I have the below String
String myStr = "rel1,wel12,val1";
Now I need to check if the String has anyone one of the elements of the list(in the above case its true as it has val1, next is get that value into a variable
I have tried the below and it works, but I'm sure there is a better way to do that using any of the Collections libraries
List<String> list = List.of("val1", "val2", "val3");
String myStr = "rel1,wel12,val1";
String matchedStr =StringUtils.EMPTY;
String[] vals = myStr.split(",");
for(String val:vals) {
if(list.contains(val){
matchedStr=val;
break;
}
}
You can use Java Streams to get the first String that match:
Optional<String> result = Stream.of(vals).filter(list::contains).findFirst();
Your way is alright if the lists aren't too big. I am considering the string as a list too because it can be made one from splitting it as you've done already. You can make a set from the bigger one, and iterate on the smaller one.
Another way to go would be to find the intersection of two lists.
List<String> list = Arrays.asList("red", "blue", "blue", "green", "red");
List<String> otherList = Arrays.asList("red", "green", "green", "yellow");
Now we can find the inttersection:
Set<String> result = list.stream()
.distinct()
.filter(otherList::contains)
.collect(Collectors.toSet());
The result should contain "red" and "green".
Some more info on collectors.
Depending on the possible values in the problem domain, there may be no need to split the input string. Just call String#contains.
If so, you can flip your logic. Rather than loop on the split parts, loop on the target list of strings. For each string in the list, ask if your unprocessed input string contains that element. If yes, bail out of the loop.
Tip: If this code is in a method returning a string, and returns null if no match was found, learn about returning an Optional.
I would favour Zobayer's answer, or using List#retainAll.
final List<String> first = List.of("one", "two", "three");
final List<String> out = new ArrayList<>(Arrays.asList("five,four,three".split(",")));
out.retainAll(first);
out contains the single entry, "three".
I'm very new to Java, and I would like your inputs.
So, I have an array:
String[] names = {"Anna", "Jo"};
String[] newNames = {"Bob", "Sue", "Jane"};
int totalLength = names.length + newNames.length;
String[] allNames = new String[totalLength];
And I am combining them through:
for (int i = 0; i < names.length; i++) {
allNames[i] = names[i];
}
for (int i = 0; i < newNames.length; i++}
allNames[i + names.length] = newNames[i];
}
My question is how do I set the allNames array into the original names array? Like, names would be "Anna", "Jo", "Bob", "Sue", "Jane". I know that there are methods that can do this, but how would you do it manually?
First and preferred option is:
name = (String[])ArrayUtils.addAll(names, newNames);
second one could be what you are doing just add:
name = newName;
after for loops.
Just assign allNames to names:
names = allNames;
System.out.println(Arrays.toString(names));
Or simply use clone method:
names = allNames.clone();
System.out.println(Arrays.toString(names));
Or use Arrays.copyOf:
names = Arrays.copyOf(allNames, allNames.length);
System.out.println(Arrays.toString(names));
Or use System.arraycopy:
names = new String[allNames.length];
System.arraycopy(allNames, 0, names, 0, allNames.length);
System.out.println(Arrays.toString(names));
Or with Java 8:
names = Arrays.stream(allNames).toArray(String[]::new);
System.out.println(Arrays.toString(names));
All variants will get the job done:
[Anna, Jo, Bob, Sue, Jane]
However, using first way you will just point reference of names to allNames. All other variants - new array will be created and populated with allNames values. The last behavior is usually preferable.
There is the Arrays class that provides functions for such things as copying. Java programmers will generally search the javadoc in the web, or maybe in the IDE.
The answer would be:
names = allNames;
But working so is quite inefficient, exchanging entire array values.
In this case, as in java arrays are fixed size, one would use a dynamic List or Set (for unique elements):
List<String> names = new ArrayList<>();
Collections.addAll(names, "Anna", "Jo");
List<String> newNames = Arrays.asList("Bob", "Sue", "Jane");
List<String> allNames = new ArrayList(names);
allNames.addAll(newNames);
In general arrays have fixed size. When you resize an array you copy all the data into a new one. So there is no way to do this when you dont init them with a larger size. The methods from the other answers will probably do what you want, but they do not expand your original array.
arrays, in Java, are objects. So, simply setting names = allNames actually has them pointing to the very same object (not separate identical copies). In other words, if you were to change "Sue" to "Suzy" in one, it would change it in the other.
This is the simplest and most efficient way to do it, assuming you don't need to use them separately.
So I am trying to create an for loop to find unique elements in a ArrayList.
I already have a ArrayList stored with user input of 20 places (repeats are allowed) but I am stuck on how to count the number of different places inputted in the list excluding duplicates. (i would like to avoid using hash)
Input:
[park, park, sea, beach, town]
Output:
[Number of unique places = 4]
Heres a rough example of the code I'm trying to make:
public static void main(String[] args) {
ArrayList<City> place = new ArrayList();
Scanner sc = new Scanner(System.in);
for(...) { // this is just to receive 20 inputs from users using the scanner
...
}
# This is where i am lost on creating a for loop...
}
you can use a Set for that.
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html
Store the list data to the Set.Set will not have duplicates in it, so the size of set will be the elements without duplicates.
use this method to get the set size.
https://docs.oracle.com/javase/7/docs/api/java/util/Set.html#size()
Sample Code.
List<String> citiesWithDuplicates =
Arrays.asList(new String[] {"park", "park", "sea", "beach", "town"});
Set<String> cities = new HashSet<>(citiesWithDuplicates);
System.out.println("Number of unique places = " + cities.size());
If you are able to use Java 8, you can use the distinct method of Java streams:
int numOfUniquePlaces = list.stream().distinct().count();
Otherwise, using a set is the easiest solution. Since you don't want to use "hash", use a TreeSet (although HashSet is in most cases the better solution). If that is not an option either, you'll have to manually check for each element whether it's a duplicate or not.
One way that comes to mind (without using Set or hashvalues) is to make a second list.
ArrayList<City> places = new ArrayList<>();
//Fill array
ArrayList<String> uniquePlaces = new ArrayList<>();
for (City city : places){
if (!uniquePlaces.contains(city.getPlace())){
uniquePlaces.add(city.getPlace());
}
}
//number of unique places:
int uniqueCount = uniquePlaces.size();
Note that this is not super efficient =D
If you do not want to use implementations of Set or Map interfaces (that would solve you problem with one line of code) and you want to stuck with ArrayList, I suggest use something like Collections.sort() method. It will sort you elements. Then iterate through the sorted array and compare and count duplicates. This trick can make solving your iteration problem easier.
Anyway, I strongly recommend using one of the implementations of Set interface.
Use following answer. This will add last duplicate element in distinct list if there are multiple duplicate elements.
List<String> citiesWithDuplicates = Arrays.asList(new String[] {
"park", "park", "sea", "beach", "town", "park", "beach" });
List<String> distinctCities = new ArrayList<String>();
int currentIndex = 0;
for (String city : citiesWithDuplicates) {
int index = citiesWithDuplicates.lastIndexOf(city);
if (index == currentIndex) {
distinctCities.add(city);
}
currentIndex++;
}
System.out.println("[ Number of unique places = "
+ distinctCities.size() + "]");
Well if you do not want to use any HashSets or similar options, a quick and dirty nested for-loop like this for example does the trick (it is just slow as hell if you have a lot of items (20 would be just fine)):
int differentCount=0;
for(City city1 : place){
boolean same=false;
for(City city2 : place){
if(city1.equals(city2)){
same=true;
break;
}
}
if(!same)
differentCount++;
}
System.out.printf("Number of unique places = %d\n",differentCount);
I am trying to add 100 (realistically more) Strings to an ArrayList. Instead of adding each String individually, how can I use something like a for loop to add them at once. The code below is an example.
ArrayList<String> strings = new ArrayList();
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
/*
More Strings created until the 100th String
.
.
.
*/
String s100 = "Kiwi";
//for loop to try add each String to List
for(int i=0; i<100; i++)
{
//Code to add each String to the arraylist
}
Can anyone identify the how I can add each String to the list?
Thanks much appreciated
Well, you could create a sophisticated strategy using reflection to fetch all variables of a given class and add them to a List; subsequently, you could loop this List and do whatever you want.
However, I do not think it would solve your problem. Indeed, you are likely to run into several pitfalls.
I would change your approach to the problem. Create a static List and add whatever you need there (or a Singleton, it depends how you want to manage this List). Once you have the list of objects you can loop it.
Cheers,
From your comments you are dealing with custom objects. Regardless of how you want to transfer data from the objects into your ArrayList, better to use a collection. The type of the collection will depend on the source of your object data. As the data is hard-coded you could use an array. Multiple variables like these
String s1 = "Apple";
String s2 = "Banana";
String s3 = "Pear"
become
String[] fruitArray = {
"Apple",
"Banana",
"Pear"
...
};
Then to add:
for (String fruit: fruitArray) {
strings.add(fruit);
}
As already stated my comment above, a cleaner design would be to to use a single List<MyObject> to contain all objects in a DRY approach and just extract a String as needed.
I dont know how to do this. But what i want is to create a two array.. one for the array class then the other is for the information that i will use for the selected class using for loop. I prefer for loop that for each loop.. ^_^.. My question is. Is it posible to create an array in which it will store an array too? for example:
private final Class<?>[] cls = {class1,class2,class3};
private final String[] myFirstArray = {array1[],array2[],array[]3};
private final String selectedarray[];
for(int i=0;i<cls.lenght();i++){
if(myArrayClassParameter == cls[i]){
selectedArray[] = myFirstArray[i];
}
}
Like that?
Well If it is posible my work will be less time consuming.. thanks.
Absolutely - you can create arrays of arrays, or even arrays of arrays of arrays, and so on. All you need is to add more pairs of square brackets [].
private final String[][] firstArray = new String[][] {
new String[] {"quick", "brown", "fox"}
, new String[] {"jumps", "over", "the"}
, new String[] {"lazy", "dog", "!"}
};
String[] selectedArray = firstArray[1];
Yes. These are called multidimensional arrays. Try them out and mess around with them. You'll learn better that way.
You must declare them like this:
Type[] smallerArray1;
Type[] smallerArray2;
Type[] smallerArray3;
Type[][] biggerArray = new Type[][]{smallerArray1, smallerArray2, smallerArray3};
Then you can use them like regular arrays.