I have an two array lists with multiple values at single index. I am adding the values like below:
ArrayList<String> list1 = new ArrayList<String>();
list1.addAll(Arrays.asList("iFRa1wVJ","Breakfast","7:00am","8:30am"));
list1.addAll(Arrays.asList("JyvmCZhw","Lunch","1:00pm","3:00pm"));
list1.addAll(Arrays.asList("HR6ovPjE","Dinner","7:30pm","9:30pm"));
ArrayList<String> list2 = new ArrayList<String>();
list2.addAll(Arrays.asList("iFRa1wVJ","Breakfast1","9:00am","10:30am"));
list2.addAll(Arrays.asList("JyvmCZhw","Lunch","2:00pm","3:00pm"));
list2.addAll(Arrays.asList("HR6ovPjE","Dinner","8:30pm","9:30pm"));
Expected result is as below:
iFRa1wVJ,Breakfast,7:00am,8:30am --> Breakfast1 is overwriiten as Breakfast from list1
JyvmCZhw,Lunch,1:00pm,3:00pm --> 2:00pm is overwriiten as 1:00pm from list1
HR6ovPjE,Dinner,7:30pm,9:30pm --> 8:30pm is overwriiten as 7:30pm from list1
I need to compare the values of each index and update the second list with the values of first list. How to do the comparisons of the list in each index. Any help will appreciated. Thanks.
It sounds as though you'd be better off using a Map or Set instead of a List. For example:
class Meal {
//You may want to store times in a different format, i.e. a long in millisecond
private final String name, startTime, endTime;
Meal(String name, String startTime, String endTime) {
this.name = name;
this.startTime = startTime;
this.endTime = endTime;
}
//getName(), getStartTime(), getEndTime()...
}
And in your map...
final Map<String, Meal> map = new HashMap<>();
map.put("iFRa1wVJ", new Meal("Breakfast","7:00am","8:30am"));
map.put("iFRa1wVJ", new Meal("Breakfast","9:00am","10:30am"));
The second "Breakfast" will replace the first as they share the same key.
You wanted two array lists with multiple values at each index, but in your original code ArrayList<String> is just an array with a single String object at each index. So I changed the data structure to hold a list of Strings. If all you really want to do is update each index with the value at the corresponding index of list1 you can just update everything at the index.
ArrayList<List<String>> list1 = new ArrayList<List<String>>();
list1.add(Arrays.asList("iFRa1wVJ", "Breakfast", "7:00am", "8:30am"));
list1.add(Arrays.asList("JyvmCZhw", "Lunch", "1:00pm", "3:00pm"));
list1.add(Arrays.asList("HR6ovPjE", "Dinner", "7:30pm", "9:30pm"));
ArrayList<List<String>> list2 = new ArrayList<List<String>>();
list2.add(Arrays.asList("iFRa1wVJ", "Breakfast1", "9:00am", "10:30am"));
list2.add(Arrays.asList("JyvmCZhw", "Lunch", "2:00pm", "4:00pm"));
list2.add(Arrays.asList("HR6ovPjE", "Dinner", "8:30pm", "9:30pm"));
for (int i = 0; i < list1.size(); i++) {
list2.set(i, list1.get(i));
}
System.out.println(list1);
Related
I have a problem where I want to keep the original arraylist and want to make two separate arraylist where one doesn't contain any duplicates and the other the amount of items in the first arraylist.
For example:
ArrayList<Item> items = new ArrayList<Item>();
ArrayList<Item> items2 = new ArrayList<Item>();
ArrayList<Item> occurences = new ArrayList<Item>();
items[0, 1, 2] would have bandana bandana bandana
items2[0] would have bandana
occurences[0] would have 3
Below code shows an example of what you need but instead of Item (I don't know if you put it as example or it's your class) there are String to store elements and Integer for occurences.
To store elements without duplicates I suggest to use Set
public static void main(String[] args) {
ArrayList<String> items = new ArrayList<String>();
ArrayList<String> items2 = new ArrayList<String>();
ArrayList<Integer> occurences = new ArrayList<Integer>();
items.add("bandana");
items.add("bandana");
items.add("bandana");
items2.addAll(new HashSet<>(items)); // create Hashset to remove duplicates and add again to Arraylist
occurences.add(items.size()); // add size of items list as first element
items.forEach(System.out::println); // Print: "bandana" "bandana" "bandana"
items2.forEach(System.out::println); // Print: "bandana"
occurences.forEach(System.out::println); // Print: 1
}
This is probably not the most efficient way of doing it but I would try something like this:
ArrayList<Item> items = new ArrayList<Item>();
ArrayList<Item> items2 = new ArrayList<Item>();
ArrayList<Item> occurences = new ArrayList<Item>();
for(int i=0; i<items.size(); i++)
{
Item x = items.get(i);
int count=1;
if(!items2.contains(x))
{
items2.add(x);
for(int j=i+1; j<items.size(); j++)
{
if(items2.get(j)==x)
count++;
}
ocurrences.add(count);
}
}
You might want to change Item to int for the occurrences list.
No Duplicates in Collection
For the collection that should have no duplicate Items, use a Set<Item> instead of an ArrayList<Item>. The Set data structure will not store duplicates. Since Item is a custom object you created, you will need to override the hashCode and equals method in your Item class.
This approach is O(1) - which is way better than keep an ArrayList<Item> and iterating it and searching for a duplicate (which will be O(n) at worst).
Occurrences
For the occurrences problem, instead of keeping your items in an ArrayList<Item>, keep them in a Map<Item,Integer>. This will map the item to how many occurrences there are of it.
Using the map, you will need to get the key, which is the Item you are about to add. If it already exists in the map, simply add one to the value of that key (the occurrences number).
If they key doesn't exist yet (this is the first time this Item will be inserted into the map), simply add it to the map, and set the value as 1.
Using a map will also be a way more efficient solution, as it will also be O(1), instead of O(n) if an ArrayList<Item> will be used.
Example:
Set<Item> itemSet = new HashSet<>();
Map<Item,Integer> occurencesMap = new HashMap<>();
itemSet.add(yourItem);
itemSet.add(yourItem);
itemSet.add(secondItem);
//itemSet now contains only 2 objects!
if (occurencesMap.get(yourItem) == null){
occurencesMap.put(yourItem,1);
}
else{
//adding 1 to the current value of occurences for that item.
occurencesMap.get(yourItem)++;
}
This is my solution using streams and lambda functions. I moddified occurence to be a Map<Item, Integer> so that we can count per item
items.stream().forEach( i -> {
if (!items2.contains(i)) {
items2.add(i);
}
occurences.merge(i, 1, Integer::sum);
});
The very cool use of merge was found in this answer. Since we don't know what Item i I tested this using String instead so equals etc worked properly
Using lambdas to get a list of distinct values:
ArrayList items2 = items.stream().distinct().collect(Collectors.toCollection(ArrayList::new)));
If I understood correctly you need the number of occurrences for each item:
Map<Item, Integer> m = new HashMap();
items.stream().forEach(k-> m.merge(k,1, Integer::sum));
ArrayList occurrences = new ArrayList(m.values());
The order in occurrences does not reflect the order of the items.
You can generate each list as below,
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
public class Main
{
public static void main(String args[])
{
ArrayList<String> items = new ArrayList<>();
ArrayList<String> items2 = new ArrayList<>();
ArrayList<Integer> occurrences = new ArrayList<>();
items.addAll(Arrays.asList("bandana", "bandana", "bandana", "abc", "abc"));
items2.addAll(new LinkedHashSet<>(items));
for (String item : items2)
{
occurrences.add(Collections.frequency(items, item));
}
System.out.println(items);
System.out.println(items2);
System.out.println(occurrences);
}
}
Assuming you can use Java 8 streams you could also do it this way:
List<String> items = Arrays.asList("bandana", "helmet", "bandana",
"bandana", "silk hat", "basecap", "silk hat");
Map<String, Long> result = items.stream().collect(
Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(result); //prints {silk hat=2, helmet=1, bandana=3, basecap=1}
Instead of two lists with the distinct values and the occurences you will have a map with the item itself as key (Function.identity()) and the number of occurences as the value (Collectors.counting()).
I am having issue to store all values of ArrayList<ArrayList<String>> into ArrayList<String>. Here stylistIDArray and durationArray are array of array. I want to store all their values in stylistId and duration respectively. The stylistid and duration are array of string.
Here's my attempt, but it stores only the last item of each array of array.
ArrayList<ArrayList<String>> stylistIDArray;
ArrayList<ArrayList<String>> durationArray;
stylistIDArray = differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray = differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String>stylistId = new ArrayList<>();
ArrayList<String>duration = new ArrayList<>();
for(int i=0; i<stylistIDArray.size(); i++) {
stylistId = stylistIDArray.get(i);
duration = durationArray.get(i);
}
Note : I have already tried this, but doesn't work for me.
To be generic, First let be an list of list of objects
List<List<Object>> listOfList;
That you want to put into a list of object
List<Object> result;
Note the result list will contain every object contain is the input list. This transformation will loose the information of which object was in which list.
You have to loop through the listOfList. At each loop you obtain a list of object (List<Object> listOfObject). Then loop through these lists to obtain every object (Object o). Then add these object to the result list (result.add(o)).
for(List<Object> listOfObject : listOfList) {
for(Object o : listOfObject) {
result.add(o);
}
}
In your case, the problem is that you use affectation instead of add(). At every loop this replaces the value by the new one. So at the end you have stored only the last item of each list.
stylistId=stylistIDArray.get(i); //This replace the existing stylistId
Instead try something like
ArrayList<ArrayList<String>> stylistIDArray;
ArrayList<ArrayList<String>> durationArray;
stylistIDArray = differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray = differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String> stylistId = new ArrayList<>();
ArrayList<String> duration = new ArrayList<>();
for(ArrayList<String> l : stylistIDArray) {
for(String s : l) {
stylistId.add(s);
}
}
for(ArrayList<String> l : durationArray ) {
for(String s : l) {
duration.add(s);
}
}
You doing wrong operation with arraylist, in loop you are getting data from stylistIDArray and assign to aryalist, not inserting in list, have look this
stylistIDArray=differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray=differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String>stylistId=new ArrayList<>();
ArrayList<String>duration=new ArrayList<>();
for(int i=0; i<stylistIDArray.size(); i++) {
stylistId.add(stylistIDArray.get(i));
duration.add(durationArray.get(i));
}
Hope it will help you!
I'm successfully getting the values from CSV file in to List<String[]>, but having problem in moving values from List<String[]> to String[] or to get single value from List. I want to copy these values in to string array to perform some functions on it.
My values are in scoreList
final List<String[]> scoreList = csvFile.read();
Now I want to get single value from this scoreList. I have tried this approaches but could not get the value
String[] value=scoreList.get(1);
You want a single value but you are declearing an array an you are tring to assign string to string array. If you want a single value, try this;
String x = scoreList.get(1);
or
if you want to convert listarray to string array try this;
String[] myArray = new String[scoreList.size()];
for(int i=0; i<scoreList.size();i++)
{
myArray[i]=scoreList.get(i);
}
Suppose you want to collect values of the 2nd column (index 1) then you can try this
// Collect values to this list.
List<String> scores = new ArrayList<String>();
final List<String[]> scoreList = csvFile.read();
// For each row in the csv file
for (String [] scoreRow : scoreList ) {
// var added here for readability. Get second column value
String value = scoreRow[1];
scores.add(value);
}
Please help me to convert ArrayList to String[]. The ArrayList contains values of type Object(VO).
For example,
The problem is that I need to convert a country List to String Array, sort it and then put it in a list. However I am getting a ClassCastException.
String [] countriesArray = countryList.toArray(new String[countryList.size()]);
I have assumed that your country List name is countryList.
So to convert ArrayList of any class into array use following code. Convert T into the class whose arrays you want to create.
List<T> list = new ArrayList<T>();
T [] countries = list.toArray(new T[list.size()]);
Please help me to convert ArrayList to String[], ArrayList Contains
Values Object(VO) as Values.
As you mentioned that list contains Values Object i.e. your own class you need toString() overridden to make this work correctly.
This code works. Assuming VO is your Value Object class.
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] result = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
result[i] = listOfValueObject.get(i).toString();
}
Arrays.sort(result);
List<String> sortedList = Arrays.asList(result);
The snippet of
List<VO> listOfValueObject = new ArrayList<VO>();
listOfValueObject.add(new VO());
String[] countriesArray = listOfValueObject.toArray(new String[listOfValueObject.size()]);
will give you ArrayStoreException due VO is not the String type as required by native method arraycopy subsequently called from toArray one.
In case your ArrayList contains Strings, you can simply use the toArray method:
String[] array = list.toArray( new String[list.size()] );
If that is not the case (as your question is not completely clear on this), you will have to manually loop over all elements
List<MyRandomObject> list;
String[] array = new String[list.size() ];
for( int i = 0; i < list.size(); i++ ){
MyRandomObject listElement = list.get(i);
array[i] = convertObjectToString( listElement );
}
String[] array = list.toArray(new String[list.size()]);
What are we doing here:
String[] array is the String array you need to convert your
ArrayList to
list is your ArrayList of VO objects that you have in hand
List#toArray(String[] object) is the method to convert List objects
to Array objects
As correctly suggested by Viktor, I have edited my snippet.
The is a method in ArrayList(toArray) like:
List<VO> listOfValueObject // is your value object
String[] countries = new String[listOfValueObject.size()];
for (int i = 0; i < listOfValueObject.size(); i++) {
countries[i] = listOfValueObject.get(i).toString();
}
Then to sort you have::
Arrays.sort(countries);
Then re-converting to List like ::
List<String> countryList = Arrays.asList(countries);
Prior to Java 8 we have the option of iterating the list and populating the array, but with Java 8 we have the option of using stream as well. Check the following code:
//Populate few country objects where Country class stores name of country in field name.
List<Country> countries = new ArrayList<>();
countries.add(new Country("India"));
countries.add(new Country("USA"));
countries.add(new Country("Japan"));
// Iterate over list
String[] countryArray = new String[countries.size()];
int index = 0;
for (Country country : countries) {
countryArray[index] = country.getName();
index++;
}
// Java 8 has option of streams to get same size array
String[] stringArrayUsingStream = countries.stream().map(c->c.getName()).toArray(String[]::new);
I have an ArrayList named play_viewCount: I am sorting this ArrryList and storing it in a new ArrayList.
Now I have sorted ArrayList: but what I want is before sorting what was the position of new items in ArrayList?
ArrayList<String> sort_play_viewCount = play_ViewCount; // here play_viewCount is ArrayList
ArrayList<Integer> position_array = new ArrayList<Integer>();
System.out.println("......................................... Play Count :"+sort_play_viewCount);
Collections.sort(sort_play_viewCount);
System.out.println(".........................................sort Play Count :"+sort_play_viewCount);
for(int j = 0; j<sort_play_viewCount.size(); j++){
for(int k = 0; k<sort_play_viewCount.size(); k++){
if(play_ViewCount.contains(sort_play_viewCount.get(j))){
position_array.add(k);
}
}
}
System.out.println(" .................Position Array: "+position_array);
Does anyone know how to get the positions of the new items before sorting?
Try doing a little differently:
ArrayList<Integer> position_array = new ArrayList<Integer>();
position_array.addAll(play_viewCount);
Collections.sort(position_array);
Now position_array is sorted, and to get the previous positions you can just call play_viewCount.indexOf(value);
You can put the elements of the ArrayList into a Map<String, Integer> (implemented by a HashMap<String, Integer>), where the key of an entry is String element from the ArrayList and the value is Integer representing the position.
Map<String, Integer> originalPositions = new HashMap<String, Integer>();
String item = ...
String position = ...
originalPositions.put(item, position);
// do something with the ArrayList, such as sorting
Collections.sort(arrayList);
String someItem = arrayList.get(i);
int originalPosition = originalPositions.get(someItem);
And by the way, this line from your code snippet doesn't do what you think it does:
ArrayList<String> sort_play_viewCount = play_ViewCount;
It doesn't create a new ArrayList with the same contents as the original one. Instead, it just creates a new reference to the original ArrayList. Both play_ViewCount and sort_play_viewCount refer to the very same object, in other words, any changes to one of the variables (such as sorting) also affect the other one.
To create a new copy (however, it is still shallow) of an ArrayList, use the following idiom:
ArrayList<Integer> original = ...
ArrayList<Integer> copy = new ArrayList<Integer>(original);