mapping an arraylist to another arraylist in java - java

I need your help in arraylist problem. I have 2 arraylist.
ArrayList<string> a = {"fruit=apple,grape,banana;nut=pistachio,chestnut,walnut,peanut;vegetable=broccoli,carrot,cabbage,tomato"}
Arraylist<String> b = {"1:1:2 2:1:2 2:3:4 3:4:4"}
Ok, array b is represent the food in a. lets say
1:1:2 means apple:nut:carrot ,
2:1:2 means grape:pistachio:carrot,
2:3:4 means grape:walnut:tomato and
3:4:4 means banana:peanut:tomato.
Currently I have no idea at all. Hopefully you guys can help me about the idea how to do this.
Thanks in advance

Well, you currently have several problems which are probably confusing the situation:
There is no such class ArrayList<string>, I guess you mean List<string>
Currently your lists consist of a single element, which is a comma / space delimited string. You probably want something more like this:
List fruit = new List(new string[] {"apple", "grape", "banana" });
List nut = new List(new string[] {"pistachio", "chestnut", "walnut", "peanut" });
List vegetable = new List(new string[] {"broccoli", "carrot", "cabbage", "tomato" });
This gives you a list where each element is a nut, fruit or vegetable respectively.
Also your second list should probably look more like this:
List<int[]> combinations = new List<int[]>(
new int[][]
{
new int[] {1, 1, 2},
new int[] {2, 1, 2},
new int[] {2, 3, 4},
new int[] {3, 4, 4},
});
I.e. conbinations is a list of combinations, where each combination consists of 3 integers - the index of each element in the list. (This is possibly a tad confusing and by no means the only option - ask if this bit isn't clear).
In face as arrays are 0-indexed in c#, in fact you probably want this instead:
List<int[]> combinations = new List<int[]>(
new int[][]
{
new int[] {0, 0, 1},
new int[] {1, 0, 1},
new int[] {1, 2, 3},
new int[] {2, 3, 3},
});
This at least makes your data easier to work with, so the only questions remaining are:
How do you get from what you have to the above? (I'll let you have a go at that yourself).
What is it that you are trying to do?

Try Below code it works as expected let me know it it does not fulfill use case.
public static List<String> fruits = new ArrayList<String>();
public static List<String> nuts = new ArrayList<String>();
public static List<String> vegitables = new ArrayList<String>();
/**
* #param args
* #throws ParseException
* #author Rais.Alam
*/
public static void main(String[] args) throws ParseException
{
fruits.add("apple");
fruits.add("grape");
fruits.add("banana");
nuts.add("pistachio");
nuts.add("chestnut");
nuts.add("walnut");
nuts.add("peanut");
vegitables.add("broccoli");
vegitables.add("carrot");
vegitables.add("cabbage");
vegitables.add("tomato");
System.out.println(getValue("1:1:2"));
System.out.println(getValue("2:1:2"));
System.out.println(getValue("2:3:4"));
System.out.println(getValue("3:4:4"));
}
public static String getValue(String key)
{
String returnString = "";
String[] arr = key.split(":");
returnString += fruits.get(Integer.parseInt(arr[0]) - 1) == null ? "" : fruits.get(Integer.parseInt(arr[0]) - 1) + ":";
returnString += nuts.get(Integer.parseInt(arr[1]) - 1) == null ? "" : nuts.get(Integer.parseInt(arr[1]) - 1) + ":";
returnString += vegitables.get(Integer.parseInt(arr[2]) - 1) == null ? "" : vegitables.get(Integer.parseInt(arr[2]) - 1);
return returnString;
}
After running the program you will get below output
apple:pistachio:carrot
grape:pistachio:carrot
grape:walnut:tomato
banana:peanut:tomato

Related

How to iterate an object array in java? [duplicate]

This question already has answers here:
Flatten nested arrays in java
(9 answers)
Closed 3 months ago.
This question was asked to me in Razorpay. I could not come up with a solution. Can anyone help me in writing Java code for this.
Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10};
Answer should be:
Integer[] = {1,2,3,4,5,6,7,8,9,10};
i.e. all the Integer elements should be stored
What I did is
for(Object obj: array){
if(obj instanceof Integer) list.add((int)(obj));
}
Which results in -> 1,2,8,9,10. How do I add 3,4,5,6,7 inside list?
As there's no finite depth of nesting of Object[] you'll need a recursive approach:
import java.util.ArrayList;
import java.util.List;
public class Answer {
static void extractIntegers(Object[] source, List<Integer> destination) {
for (Object i : source) {
if (i instanceof Object[] array) {
extractIntegers(array, destination);
} else if (i instanceof Integer integer) {
destination.add(integer);
} else {
throw new IllegalArgumentException("Unexpected: " + i);
}
}
}
public static void main(String[] args) {
List<Integer> ints = new ArrayList<>();
Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10};
extractIntegers(array, ints);
System.out.println(ints);
}
}
Note that I'm using the recently added "pattern matching for instanceof" feature of Java.
You could ignore objects which are not Object[] or Integer. I've chosen to throw an excpetion.
The operation you are looking for is called flattening an array. Your input is an array of Object which can consist of either Integer or Object[]. So we have to handle both cases here, and it is easier done with recursion:
Write a function flatten(Object[] arr) that takes in an Object[] as parameter. The function will return List<Integer> which is the result after arr is flattened.
The logic is simple for the recursive flatten() function:
create empty result_array
for each obj in Object[]:
if obj is an Integer:
add obj to the result_array
else obj is Object[]:
flat_obj := flatten(obj)
add all integers of flat_obj into result_array
return result_array
Here are the Java code for the above logic implemented. Hope it helps!
public class Test {
public static List<Integer> flatten(Object[] array) {
List<Integer> result = new ArrayList<>();
for (Object o: array) {
if (o instanceof Object[])
result.addAll( flatten( (Object[]) o) );
else
result.add((Integer) o);
}
return result;
}
public static void main(String[] args) {
Object[] array = { 1, 2, new Object[]{ 3, 4, new Object[]{ 5 }, 6, 7 }, 8, 9, 10};
System.out.println( flatten(array) );
}
}
You're only checking for integers, but you also have arrays in your array.
Together with the instanceof Integer check, you should also add a check on instanceof Object[]. Be careful that also the Object[] contains an Object[]. So you'll have to have the same check inside of it as well. You shall have 3 loops in the end, each of which will have checks on instanceof Integer and instanceof Object[]

List of int array in Java

How do I print the contents of a List that contains a primitive type int object in it? Prefer answers to print this in one line. This is the code I have.
public static void main(String[] args) {
List<int[]> outputList = new ArrayList<>();
int[] result = new int[] { 0, 1 };
int[] result2 = new int[] { 2, 3 };
outputList.add(result);
outputList.add(result2);
System.out.println(Arrays.toString(outputList.get(0)));
}
This will give me [0,1] but I am looking for {[0,1],[2,3]}
The following one-liner can meet your requirement:
System.out.println(
Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{").replaceAll("\\](?=$)", "}"));
It uses the positive lookbehind and positive lookahead regex assertions. Note that ^ is used for the start of the text and $ is used for the end of the text. The Arrays.deepToString(outputList.toArray()) gives us the string, [[0, 1], [2, 3]] and this solution replaces [ at the start of this string and ] at the end of this string, with { and } respectively.
In case, you want to remove all whitespace as well, you can chain one more replacement as follows:
System.out.println(Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{")
.replaceAll("\\](?=$)", "}").replace(" ", ""));
Demo:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
List<int[]> outputList = new ArrayList<>();
int[] result = new int[] { 0, 1 };
int[] result2 = new int[] { 2, 3 };
outputList.add(result);
outputList.add(result2);
System.out.println(
Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{").replaceAll("\\](?=$)", "}"));
System.out.println(Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{")
.replaceAll("\\](?=$)", "}").replace(" ", ""));
}
}
Output:
{[0, 1], [2, 3]}
{[0,1],[2,3]}
ONLINE DEMO
You can do it by using StringBuffer class
public static void main(String[] args) {
List<int[]> outputList = new ArrayList<>();
int[] result = new int[]{0, 1};
int[] result2 = new int[]{2, 3};
outputList.add(result);
outputList.add(result2);
StringBuffer output=new StringBuffer();
for (int[] ints : outputList) output.append(Arrays.toString(ints)).append(",");
output.insert(0,"{");
output.replace(output.capacity()-2,output.capacity()-1,"}");
System.out.println(output);
}
Output:
{[0, 1],[2, 3]}
Solution
This one-liner should do it:
System.out.println(list.stream().map(Arrays::toString)
.collect(Collectors.joining(", ", "{", "}")));
(I have line-wrapped it for readability.)
Non-solutions
Since you want the outer list to be enclosed in { ... } we can't use List::toString in the Stream solution above. Likewise, Arrays::deepToString is going to give us the wrong output.
Obviously, this can be fixed using String::replace, but that strikes me as ugly. It is better to use the correct "enclosers" in the first place. (Or change the requirements!!)
Calling Arrays::toString() on an int[][] produced using List::toArray will give you this:
[[I#2a40cd94, [I#f4168b8]
... which is not even close to correct.
Arrays::toString calls toString on the int[] objects, and array classes do not override the Object::toString implementation.
Arrays::deepToString addresses that aspect of the problem.

Add an array of string to an array list of the array's of strings

So in my program I split the first row of data imported by a csv file into an array. Is there anyway that I can add this array into an array list as the first element? Because once I split the second data into an array by a delimiter I then want to store this array in the same arraylist but in element 2. A bit confusing but to summarize is nested arrays in an arraylist possible?
public static ArrayList<String[]> readCSV(Scanner csv, String delimiter, int minCellsPerRow) {
String line = csv.nextLine();
String[] parts = line.split(delimiter);
List<String> list = new ArrayList<String>();
list.add(parts);
}
you can specify insertion index with list.add()... here is an example:
public static void main(String[] args) {
//setup
ArrayList<String> storage;
storage = new ArrayList<String>(Arrays.asList("4","5","6"));
String[] data = {"1","2","3"};
printMe(storage);
//append
storage.addAll(0, Arrays.asList(data));
printMe(storage);
}
public static void printMe(ArrayList<String> strs) {
System.out.println(Arrays.toString(strs.toArray(new String[0])));
}
yields the console result:
[4, 5, 6]
[1, 2, 3, 4, 5, 6]
would this work in your case?

Sort two arrayLists concurrently

Say I have two ArrayLists:
name: [Four, Three, One, Two]
num: [4, 3, 1, 2]
If I do: Arrays.sort(num), then I have:
name: [Four, Three, One, Two]
num: [1, 2, 3, 4]
Is there any way I can possibly do a sort on num and have it reflected in name as well, so that I might end up with:
name: [One, Two, Three, Four]
num: [1, 2, 3, 4]
? Please do help me out. I thought of Comparators and Objects, but barely know them at all.
You should somehow associate name and num fields into one class and then have a list of instances of that specific class. In this class, provide a compareTo() method which checks on the numerical values. If you sort the instances, then the name fields will be in the order you desire as well.
class Entity implements Comparable<Entity> {
String name;
int num;
Entity(String name, int num) {
this.name = name;
this.num = num;
}
#Override
public int compareTo(Entity o) {
if (this.num > o.num)
return 1;
else if (this.num < o.num)
return -1;
return 0;
}
}
Test code could be like this:
public static void main(String[] args) {
List<Entity> entities = new ArrayList<Entity>();
entities.add(new Entity("One", 1));
entities.add(new Entity("Two", 2));
entities.add(new Entity("Three", 3));
entities.add(new Entity("Four", 4));
Collections.sort(entities);
for (Entity entity : entities)
System.out.print(entity.num + " => " + entity.name + " ");
}
Output:
1 => One 2 => Two 3 => Three 4 => Four
Instead of sorting the actual arrays you can have an array with just indices
a[i] = i for i = 0..n
and you can sort this array based on your numeruc array with a custom comparator. e.g.
bool compare( int a, int b ) { return num[a] < num[b]; }
Thus you have both arrays sorted by using these indices.
If you don't have repeated elements, then you could just use a sorted Map like a TreeMap instead:
int[] num = {4, 3, 1, 2};
String[] name = {"Four", "Three", "One", "Two"};
TreeMap<Integer,String> sortedMap = new TreeMap<Integer,String>();
for (int i=0; i<num.length; i++) sortedMap.put(num[i], name[i]);
// Resulting sortedMap: {1=One, 2=Two, 3=Three, 4=Four}
If you do have repeated elements then this won't work because the keys of the map must be unique.
In some cases it doesn't make much sense to create a new class just to do multiple sorts based off a given list. I've created a function that does this, but I've posted the code in a another SO post so I wont repeat it. Below is an example of how to use it.
Usage
Here is an example of how you can use the function to sort multiple lists of arbitrary types:
// The key can be any type that implements Comparable, Dupes are allowed
List<Integer> key = Arrays.asList(4, 3, 1, 2, 1);
// List Types do not need to be the same
List<String> list1 = Arrays.asList("Four", "Three", "One", "Two", "One");
List<Character> list2 = Arrays.asList('d', 'c', 'a', 'b', 'a');
// Sorts key, list1, list2 using key as the sorting key.
keySort(key, key, list1, list2);
Output:
key: [1, 1, 2, 3, 4]
list1: [One, One, Two, Three, Four]
list2: [a, a, b, c, d]

find out the elements of an arraylist which is not present in another arraylist

I have to find a best way to find out that elements which is not presented in the second arraylist.
suppose
Arraylist a,b,
Arraylist a={1,2,3,4,5};
Arraylist b={2,3,4};
So basically what I want is to find out that elements of a which is not present in arraylist b.
So what is the best solutions to do that?
List<Integer> c = new ArrayList<>(a);
c.removeAll(b);
Also consider to use Sets instead of Lists.
here is another approach using java 8 -
a.stream().filter(b::contains).collect(Collectors.toList());
You could use Apache Commons Collections, which has a method explicitly for this purpose:
public static void main(String[] args) {
List<Integer> a = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
List<Integer> b = Arrays.asList(new Integer[] { 2, 3, 4 });
Collection<Integer> aMinusB = CollectionUtils.subtract(a, b);
System.out.println(aMinusB);
}
The printed result is: [1, 5].
The Apache Commons libs are well tested and commonly used to extend standard Java functionalities. This particular method accepts Iterable as parameters, so you can use any Collection you want. You can also mix different collection types:
public static void main(String[] args) {
List<Integer> a = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
Set<Integer> b = new HashSet<Integer>(Arrays.asList(new Integer[] { 2, 3, 4 }));
Collection<Integer> aMinusB = CollectionUtils.subtract(a, b);
System.out.println(aMinusB);
}
The printed result is the same, [1, 5].
Check out the Javadoc here.
For sake of completeness, Google's Guava library does not have this feature:
Collection *subtract*(Collection, Collection)
No equivalent--create an ArrayList containing a and then call remove on it for each element in b.
However, it implements a method called Sets.difference() method, which you could use if you prefer Guava and work with sets:
public static void main(String[] args) {
Set<Integer> a = new HashSet<Integer>(Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }));
Set<Integer> b = new HashSet<Integer>(Arrays.asList(new Integer[] { 2, 3, 4 }));
Set<Integer> aMinusB = Sets.difference(a, b);
System.out.println(aMinusB);
}
The result is all elements in a that doesn't exist in b (i.e. [1, 5] again). Of course, the order is not determined since it operates on sets.
You can try removeAll:
List<Integer> notPresent = new ArrayList<Integer>(a);
notPresent.removeAll(b);
Use org.apache.commons.collections4.ListUtils
Given
List<Integer> a = Arrays.asList(new Integer[]{ 1,2,3,4,5});
List<Integer> b = Arrays.asList(new Integer[]{0,1,2,3});
Action
List<Integer> c = ListUtils.removeAll(b, a)
Result in List c
4, 5
Please try like this
for (Object o : a) {
if (!b.contains(o)) {
// this is not present
}
}
Loop through one list, then check if each element in other list using contains.
Something like this. If you think there may be duplicates in a you can try another type of Collection, like a Set for notPresent.
List<Integer> notPresent = new ArrayList<Integer>();
for (Integer n : a){
if (!b.contains(n)){
notPresent.add(n);
}
}
Try this:
public static void main(String[] args) {
List<Integer> a = new ArrayList<Integer>();
List<Integer> b = new ArrayList<Integer>();
List<Integer> exclusion = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
b.add(1);
b.add(2);
b.add(3);
b.add(5);
for (Integer x : a) {
if (!b.contains(x)) {
exclusion.add(x);
}
}
for (Integer x : exclusion) {
System.out.println(x);
}
}
Try this...
Use the contains() method of List.
ArrayList<Integer> aList = new ArrayList<Integer>();
for (Integer i : a){
if (!(b.contains(i))){
aList.add(i);
}
else{
continue;
}
}

Categories