Convert List<List<String>> to ArrayList<String> in Android - java

I want to convert them to ArrayList and I will store them. After that, I have to convert them into old values. Do you have any suggestions? Thanks in advance.
public List<List<String>> phones = new ArrayList<>();
public List<List<Restaurant.Menu>> menus = new ArrayList<>();
public ArrayList<String> phones = ?
public ArrayList<String> menus = ?

For the first scenario, you can flatten the phones nested list into a single list and then collect into an ArrayList.
ArrayList<String> result =
phones.stream()
.flatMap(Collection::stream)
.collect(Collectors.toCollection(ArrayList::new));
For the second scenario, you will need to extract the string representation of the Menu objects given you've overridden toString, otherwise you'll need to extract some type of property from the Menu objects in order to project from Menu to String.
Given you've overridden toString, then do it this way:
ArrayList<String> menuResult =
menus.stream()
.flatMap(Collection::stream)
.map(Menu::toString)
.collect(Collectors.toCollection(ArrayList::new));
Given you need to extract some property from menus, then do it this way:
ArrayList<String> menuResult =
menus.stream()
.flatMap(Collection::stream)
.map(Menu::getName)
.collect(Collectors.toCollection(ArrayList::new));
If your API level doesn't support these features then you can use:
// flatten List<List<String>> to ArrayList<String>
ArrayList<String> phonesAccumulator = new ArrayList<>();
for (List<String> temp : phones) {
phonesAccumulator.addAll(temp);
}
// flatten List<List<Restaurant.Menu>> to ArrayList<String>
ArrayList<String> menusAccumulator = new ArrayList<>();
for (List<Restaurant.Menu> temp : menus) {
for(Restaurant.Menu m : temp){
menusAccumulator.add(m.toString());
// or m.getName();
}
}

If you're using Java 8, flatMap can be useful here:
ArrayList<String> phoneList = phones.stream()
.flatMap(List::stream)
.collect(Collectors.toCollection(ArrayList::new));

I am proving my resolution as below said, so you can change as per your own -
List<String> nonvegList = new ArrayList<String>();
nonvegList.add("Mutton Keema");
nonvegList.add("Chicken Keema");
nonvegList.add("Korma Veg Keema");
nonvegList.add("Pulaav Biryaani");
nonvegList.add("Mutton Biryaani");
nonvegList.add("Chicken Biryaani");
List<List<String>> menuList = new ArrayList<List<String>>();
menuList.add(nonvegList);
ArrayList<String> resultList = new ArrayList<String>(menuList.get(0));
System.out.println(resultList);
sweet, simple and in understadable format, compatible after Java 6+,
hope this will help you, thanks.

I used gson to solve it. I share a sample.
Gson gson = new Gson();
ArrayList<String> gsonString = new ArrayList<>();
for(int i=0; i<restaurants.size(); i++)
gsonString.add(gson.toJson(restaurants.get(i)));
// Store it
tinydb.putListString("tinyRestaurant",gsonString);
And convert again
Gson gson = new Gson();
for(int i=0; i<tinydb.getListString("tinyRestaurant").size(); i++)
restaurants.add(gson.fromJson(tinydb.getListString("tinyRestaurant").get(i), Restaurant.class));

Related

How to merge two corresponding values of two different variables in arraylist?

I want to merge two corresponding values of two different variables with comma separator in a row :
like
Plate Numbers(Output) : MH 35353, AP 35989, NA 24455, DL 95405.
There is two different variables one is plate State and another is plate Number, I want to merge them together with their corresponding values like 1st values of plate State with 1st value of plate Number after that comma then so on..
I tried this code snippet but didn't work :
ArrayList<String>
list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA ");
list1.add("DL");
ArrayList<String>
list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
list1.addAll(list2);
use this :
ArrayList<String>
list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA ");
list1.add("DL");
ArrayList<String>
list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
Iterator iterable = list2.iterator();
List<String> list3 =list1.stream()
.map(x->{
x= x+" "+((String) iterable.next());
return x;})
.collect(Collectors.toList());
String output = String.join(", ", list3);
System.out.println(output);
From ArrayList#addAll Javadoc:
Appends all of the elements in the specified collection to the end of this list[...]
This is not what you want, because you actually don't want to append the objects, you want to merge the String of the first list with the String from the second list. So in a sense, not merge the List but merge the objects (Strings) in the lists.
The easiest (most beginner friendly) solution would be to just create a simple helper method yourself, that does what you need.
Something like this:
public static void main(String[] args) {
ArrayList<String> list1 = new ArrayList<String>();
list1.add("MH");
list1.add("AP");
list1.add("NA");
list1.add("DL");
ArrayList<String> list2 = new ArrayList<String>();
list2.add("35353");
list2.add("35989");
list2.add("24455");
list2.add("95405");
ArrayList<String> combined = combinePlateNumbers(list1, list2);
System.out.println(combined);
}
private static ArrayList<String> combinePlateNumbers(List<String> list1, List<String> list2) {
ArrayList<String> result = new ArrayList<>();
if (list1.size() != list2.size()) {
// lists don't have equal size, not compatible
// your decision on how to handle this
return result;
}
// iterate the list and combine the strings (added optional whitespace here)
for (int i = 0; i < list1.size(); i++) {
result.add(list1.get(i).concat(" ").concat(list2.get(i)));
}
return result;
}
Output:
[MH 35353, AP 35989, NA 24455, DL 95405]

Adding to list of arraylist

I am trying to add the following 2 which are stored in tempEdges:
[RoyalElephant, IS-A, Elephant]
[RoyalElephant, IS-NOT-A, Gray]
although i only want the last 2 elements of each arraylist to be added to the 2 arraylists in copiedPaths.
The arraylists are:
public static List<ArrayList<String>> copiedPaths = new ArrayList<>();
public static List<ArrayList<String>> tempEdges = new ArrayList<>();
And the dis-functional code is:
copiedPaths.get(0).add(tempEdges.get(0).get(1));
copiedPaths.get(0).add(tempEdges.get(0).get(2));
copiedPaths.get(1).add(tempEdges.get(1).get(1));
copiedPaths.get(1).add(tempEdges.get(1).get(2));
This is not working as intended as both arrays are being added with IS-NOT-A, Gray instead of one having IS-A, Elephant and the other having IS-NOT-A, Gray
ArrayList<ArrayList<String>> copiedPaths = new ArrayList<>();
ArrayList<ArrayList<String>> tempEdges = new ArrayList<>();
tempEdges.add(new ArrayList<>(Arrays.asList("RoyalElephant", "IS-A", "Elephant")));
tempEdges.add(new ArrayList<>(Arrays.asList("RoyalElephant", "IS-NOT-A", "Gray")));
copiedPaths.add(new ArrayList<>(Arrays.asList(tempEdges.get(0).get(1),tempEdges.get(0).get(2))));
copiedPaths.add(new ArrayList<>(Arrays.asList(tempEdges.get(1).get(1),tempEdges.get(1).get(2))));
System.out.println(Arrays.toString(copiedPaths.get(0).toArray()));
System.out.println(Arrays.toString(copiedPaths.get(1).toArray()));
Output:-
[IS-A, Elephant]
[IS-NOT-A, Gray]
Java 9+ solution:
List<List<String>> tempEdges = List.of(List.of("RoyalElephant", "IS-A", "Elephant"),
List.of("RoyalElephant", "IS-NOT-A", "Gray"));
List<List<String>> copiedPaths = tempEdges.stream()
.map(list -> list.subList(1, list.size()))
.collect(Collectors.toList());
System.out.println(tempEdges);
System.out.println(copiedPaths);
For Java 8+, use Arrays.asList instead of List.of.
For Java 7+, use:
List<List<String>> tempEdges = Arrays.asList(Arrays.asList("RoyalElephant", "IS-A", "Elephant"),
Arrays.asList("RoyalElephant", "IS-NOT-A", "Gray"));
List<List<String>> copiedPaths = new ArrayList<>();
for (List<String> list : tempEdges)
copiedPaths.add(list.subList(1, list.size()));
System.out.println(tempEdges);
System.out.println(copiedPaths);
Output
[[RoyalElephant, IS-A, Elephant], [RoyalElephant, IS-NOT-A, Gray]]
[[IS-A, Elephant], [IS-NOT-A, Gray]]
Note that subList creates a view of the underlying list. If the original tempEdges lists can change, you need to create a copy, i.e. change
list.subList(1, list.size())
to
new ArrayList<>(list.subList(1, list.size()))

forming new small lists from a combination set of two lists

I have two patterns of lists inside a big list.
[[5.35, 5.09, 4.95, 4.81, 4.75, 5.19], [3601.0, 3602.0, 3603.0, 3600.0, 3610.0, 3600.0],[..,..,..,],[..,..,..],...]
To put in simple words, it is a combination of
[ [pricesList1], [DurationList1], [PricesList2], [DurationList2],... ]
I now want to create a new list with the price and corresponding duration from both lists as a pair from each set. For Example :
[[[5.35,3601.0],[5.09,3602.0],[4.95,3603],[4.81,3600],[4.75,3610],....],[[p1,d1],[p2,d2],[p3,d3],..],[[],[],[],..],....]
I have tried using List<List<Object>> and List<List<String>>. But no use. How can I do this?
I programed as following, which is wrong :
List<List<Object>> DurationList = new ArrayList<List<Object>>();
List<List<Object>> FinalList = new ArrayList<List<Object>>();
List<List<String>> SlotList = null;
for(int pair=0; pair<(FinalList.size()-1) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList = new ArrayList<List<String>>();
SlotList.addAll((Collection<? extends List<String>>) (FinalList.get(pair).get(innerloop)));
}
}
for(int pair=1; pair<(FinalList.size()) ; pair=pair+2)
{
for(int innerloop=0; innerloop<(FinalList.get(pair).size());innerloop++)
{
SlotList.addAll((Collection<? extends List<Object>>) FinalList.get(pair).get(innerloop));
}
}
Assuming the input list always has an even number of sublists and pairs of sublists have the same size, you can use a for loop iterating over the outer lists's element two by two :
List<List<String>> result = new ArrayList<>();
for (int i=0; i<outerList.size(); i+=2) {
List<String> priceList = outerList.get(i);
List<String> durationsList = outerList.get(i+1);
for (int j=0; j<priceList.size(); j++) {
List<String> newEntry = new ArrayList<>();
newEntry.add(priceList.get(j));
newEntry.add(durationsList.get(j));
result.add(newEntry);
}
}
As commented I suggest defining your own class to store the price and duration rather than using that List<String> newEntry.

How to populate an ArrayList<String> from ArrayList<Object>

Is there a smarter way to populate this list of strings by getting the collection of gameList and converting the Game objects to strings?
ArrayList<Game> gameList = getAllGames();
ArrayList<String> stringList = new ArrayList<String>();
for (Game game : gameList) {
stringList.add(game.toString());
}
Using Java 8:
ArrayList<String> stringList = gameList.stream().map(Object::toString).collect(Collectors.toCollection(ArrayList::new));
(Note: I haven't yet tested this.)
You could use new Java 8 lambdas and streams:
List<String> stringList = getAllGames().stream()
.map(game -> game.toString())
.collect(Collectors.toList());
Look at that, wonderful!
Well, I would prefer to use the List interface, that way you can swap the List implementation out without changing caller code. Also, you could use the diamond operator. Finally, you could construct the new ArrayList with an optimal initial capacity -
List<Game> gameList = getAllGames();
List<String> stringList = new ArrayList<>(gameList.size());
for (Game game : gameList) {
stringList.add(game.toString());
}
Or a new helper method like,
public static List<String> getStringList(List<?> in) {
List<String> al = new ArrayList<>(in != null ? in.size() : 0);
for (Object obj : in) {
al.add(obj.toString());
}
return al;
}
then
List<String> stringList = getStringList(gameList);

How to convert a String into an ArrayList?

In my String, I can have an arbitrary number of words which are comma separated. I wanted each word added into an ArrayList. E.g.:
String s = "a,b,c,d,e,.........";
Try something like
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
Arrays.asList documentation
String.split documentation
ArrayList(Collection) constructor documentation
Demo:
String s = "lorem,ipsum,dolor,sit,amet";
List<String> myList = new ArrayList<String>(Arrays.asList(s.split(",")));
System.out.println(myList); // prints [lorem, ipsum, dolor, sit, amet]
This post has been rewritten as an article here.
String s1="[a,b,c,d]";
String replace = s1.replace("[","");
System.out.println(replace);
String replace1 = replace.replace("]","");
System.out.println(replace1);
List<String> myList = new ArrayList<String>(Arrays.asList(replace1.split(",")));
System.out.println(myList.toString());
In Java 9, using List#of, which is an Immutable List Static Factory Methods, become more simpler.
String s = "a,b,c,d,e,.........";
List<String> lst = List.of(s.split(","));
Option1:
List<String> list = Arrays.asList("hello");
Option2:
List<String> list = new ArrayList<String>(Arrays.asList("hello"));
In my opinion, Option1 is better because
we can reduce the number of ArrayList objects being created from 2 to 1. asList method creates and returns an ArrayList Object.
its performance is much better (but it returns a fixed-size list).
Please refer to the documentation here
Easier to understand is like this:
String s = "a,b,c,d,e";
String[] sArr = s.split(",");
List<String> sList = Arrays.asList(sArr);
Ok i'm going to extend on the answers here since a lot of the people who come here want to split the string by a whitespace. This is how it's done:
List<String> List = new ArrayList<String>(Arrays.asList(s.split("\\s+")));
If you are importing or you have an array (of type string) in your code and you have to convert it into arraylist (offcourse string) then use of collections is better. like this:
String array1[] = getIntent().getExtras().getStringArray("key1"); or String array1[] = ... then
List allEds = new ArrayList(); Collections.addAll(allEds, array1);
You could use:
List<String> tokens = Arrays.stream(s.split("\\s+")).collect(Collectors.toList());
You should ask yourself if you really need the ArrayList in the first place. Very often, you're going to filter the list based on additional criteria, for which a Stream is perfect. You may want a set; you may want to filter them by means of another regular expression, etc. Java 8 provides this very useful extension, by the way, which will work on any CharSequence: https://docs.oracle.com/javase/8/docs/api/java/util/regex/Pattern.html#splitAsStream-java.lang.CharSequence-. Since you don't need the array at all, avoid creating it thus:
// This will presumably be a static final field somewhere.
Pattern splitter = Pattern.compile("\\s+");
// ...
String untokenized = reader.readLine();
Stream<String> tokens = splitter.splitAsStream(untokenized);
If you want to convert a string into a ArrayList try this:
public ArrayList<Character> convertStringToArraylist(String str) {
ArrayList<Character> charList = new ArrayList<Character>();
for(int i = 0; i<str.length();i++){
charList.add(str.charAt(i));
}
return charList;
}
But i see a string array in your example, so if you wanted to convert a string array into ArrayList use this:
public static ArrayList<String> convertStringArrayToArraylist(String[] strArr){
ArrayList<String> stringList = new ArrayList<String>();
for (String s : strArr) {
stringList.add(s);
}
return stringList;
}
Let's take a question : Reverse a String. I shall do this using stream().collect(). But first I shall change the string into an ArrayList .
public class StringReverse1 {
public static void main(String[] args) {
String a = "Gini Gina Proti";
List<String> list = new ArrayList<String>(Arrays.asList(a.split("")));
list.stream()
.collect(Collectors.toCollection( LinkedList :: new ))
.descendingIterator()
.forEachRemaining(System.out::println);
}}
/*
The output :
i
t
o
r
P
a
n
i
G
i
n
i
G
*/
This is using Gson in Kotlin
val listString = "[uno,dos,tres,cuatro,cinco]"
val gson = Gson()
val lista = gson.fromJson(listString , Array<String>::class.java).toList()
Log.e("GSON", lista[0])
I recommend use the StringTokenizer, is very efficient
List<String> list = new ArrayList<>();
StringTokenizer token = new StringTokenizer(value, LIST_SEPARATOR);
while (token.hasMoreTokens()) {
list.add(token.nextToken());
}
If you're using guava (and you should be, see effective java item #15):
ImmutableList<String> list = ImmutableList.copyOf(s.split(","));

Categories

Resources