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()))
Related
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]
Hi I have an arraylist of arraylist in this format:
[[val1, val2],[val3,val4],[val1,val2],[val1,val5]]
and would like to get the unique set of arraylists:
[[val1, val2],[val3,val4],[val1,val5]]
I have tried the following:
Set<String> uniques = new HashSet<>();
for (ArrayList<String> sublist : mappedEntities) {
uniques.addAll(sublist);
}
but this merges all the values of the internal arraylist together
can use Java 8 Collection Stream Distinct,
return in Set datatype :
Set<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toSet());
if you want return in List :
List<List<String>> uniques = mappedEntities.stream().distinct().collect(Collectors.toList());
Why not simply put them in a Set like this?
Set<List<String>> uniques = new HashSet<>(mappedEntities);
Your mistake is that you are flattening the inner lists and putting their items in the set separately.
The issue here is that you need a Set of ArrayList Set<ArrayList<String>>, but you are using a Set of Strings Set<String> instead.
Given the list :
List<List<String>> mappedEntities = Arrays.asList(Arrays.asList("val1", "val2"),
Arrays.asList("val3", "val4"),
Arrays.asList("val1", "val2"),
Arrays.asList("val1", "val5"));
All you need to do is just declare the set and use the addAll().
Set<List<String>> mySet = new HashSet<>();
mySet.addAll(mappedEntities);
Since a set can hold only unique values, all duplicates will not be added to the set (No need to explicitly check this). You can now print it out :
mySet.forEach(System.out::println);
Or more simply, initialize the HashSet using the list mappedEntities :
Set<List<String>> mySet = new HashSet<>(mappedEntities);
I am beginner on STACKOVERFLOW but i to try solve your problem
I think you want like this..
import java.util.*;
public class GFG {
public static void main(String[] args)
{
int n = 3;
// Here aList is an ArrayList of ArrayLists
ArrayList<ArrayList<String> > aList =
new ArrayList<ArrayList<String> >(n);
// Create n lists one by one and append to the
// master list (ArrayList of ArrayList)
ArrayList<String> a1 = new ArrayList<String>();
a1.add("1");
a1.add("2");
aList.add(a1);
ArrayList<String> a2 = new ArrayList<String>();
a2.add("11");
a2.add("22");
aList.add(a2);
ArrayList<String> a3 = new ArrayList<String>();
a3.add("1");
a3.add("2");
aList.add(a3);
Set<ArrayList<String>> uniques = new HashSet<ArrayList<String>>();
for (ArrayList<String> sublist : aList) {
uniques.add(sublist);
}
System.out.println("Your Answer");
for (ArrayList<String> x : uniques)
System.out.println(x);
}
}
try this code:
public class B {
public static void main(String[] args) throws Exception {
List<List<String>> list= Arrays.asList(
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c"),
Arrays.asList("a","b","c","d"));
Set<List<String>> uniques = new HashSet<>();
for (List<String> sublist : list) {
if(!uniques.contains(sublist))
uniques.add(sublist);
}
System.out.println(uniques);
}
}
output:
[[a, b, c], [a, b, c, d]]
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));
How I can group all lists in list which contains same exact value.
List<List<String>> list = new ArrayList<>();
This list contains list1 list2 list3 and etc....
I want to find if list1.get(0) is the same as list2.get(0) if no check with list3.get(0) and etc...
Later I need to group lists if I find the same values in each.
For example if true add list1 and list3 and others which were found to
List<List<String>> list2 = new ArrayList<>();
Now check with list2.get(0) if equal to others if yes group them and add them to anoter:
List<List<String>> list3 = new ArrayList<>();
What I achieved so far:
private static void findEqualLists(List<List<String>> list) {
int i = 0;
for (List<String> list1 : list) {
if (!Collections.disjoint(list1, list.get(i))) {
System.out.println(list1.get(0)+list.get(i).get(0));
}else{
System.out.println(list1.get(0)+list.get(i).get(0));
}
i++;
}
}
Value exmaple:
list = {{2017-02,jhon,car},{2017-03,maria,car},{2017-03, boy, car}, {2017-01,arya, car}, {2017-02, girl, car}}
Output:
Group1:
2017-03,maria,car
2017-03, boy, car
Group2:
2017-02,jhon,car
2017-02, girl, car
Group3
2017-01,arya, car
You want Collectors.groupingBy:
private static Map<String, List<List<String>>>
findEqualLists(List<List<String>> list) {
return list.stream().collect(Collectors.groupingBy(l -> l.get(0)));
}
The returned Map will use l.get(0) as a unique key, with each corresponding value being a List of only those Lists whose first element matches that key.
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);