Create linked lists of string arrays - java

I want to display the contents of an array of linked lists. Each linked list contains a String array. The content of the array of linked lists is displaying as [[[Ljava.lang.String;#15db9742], [[Ljava.lang.String;#6d06d69c], [[Ljava.lang.String;#7852e922]]. How do I solve this?
public class LinkedListOfStringArrays {
public static void main(String[] args) {
LinkedList<String[]> Values[] = new LinkedList[3];
for (int i = 0; i < 3; i++){
Values[i] = new LinkedList<String[]>();
}
String[] first = {"first element", "ABC"};
String[] second = {"second element", "DEF"};
String[] third = {"third element", "GHI"};
Values[0].add(first);
Values[1].add(second);
Values[2].add(third);
System.out.println(Arrays.toString(Values));
}
}

You will have to loop through the lists and output it manually:
// Loop through the Array of LinkedLists
for(LinkedList<String[]> list : Values) {
// Next loop through each of the lists
for(String[] keyValuePair : list) {
// Then output the values as you see fit
System.out.println(keyValuePair[0] + " - " + keyValuePair[1]);
}
}
This will give you the following output:
first element - ABC
second element - DEF
third element - GHI

In Java 8 you can try as
Stream.of(Values).
flatMap(list -> list.stream()).
forEach(values -> System.out.println(String.join("-",values)));

Related

Grouping the nested loop elements based on the first iteration variable in Java

I have 2 lists one for the sentence one for the keywords. The idea is to check if the sentence have the keywords. and put them in a list for each sentence in order.
I am sorry if this is already duplicated here in advance.
List <String> sentence= new ArrayList <>();
sentence.add("this is a good dog");
sentence.add("cats drink milk");
sentence.add("Animals are beautiful creatures");
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
My idea was to create 2 nested loops for each list:
for (int b = 0; b < sentence.size(); b++) {
for (int c = 0; c < keyword.size(); c++) {
if (sentence.get(b).contains(keyword.get(c))) {
System.out.println(keyword.get(c));
}
}
}
The output of this is:
dog
good
this
cats
milk
beautiful
are
The desired output would be:
[this,good,dog]
[cats,milk]
[are,beautiful]
So it is like getting all the existing keywords, in the order of the sentence,not related to keywords order.
and then group the existing keywords for each sentence, as in the order of existence.
Hope it is clear. Would really appreciate any ideas. doesnt have to follow the same method.
Iterate over your sentence list. For each sentence iterate over your keyword list. Add each found keyword found in a tempList, sort the tempList by the index of keyword in sentence and finally add each tempList to a list of lists. Example:
public static void main(String[] args) {
List <String> sentence= new ArrayList <>();
sentence.add("this is a good dog");
sentence.add("cats drink milk");
sentence.add("Animals are beautiful creatures");
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
List<List<String>> result = new LinkedList<>();
for(String sen: sentence){
List<String> tempList = new ArrayList<>();
for(String key: keyword){
if(sen.contains(key)){
tempList.add(key);
}
}
tempList.sort(new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return sen.indexOf(o1) - sen.indexOf(o2) ;
}
});
result.add(tempList);
}
for(List<String> r : result){
System.out.println(r);
}
}
You need a slight modification in your looping
for (int i = 0; i < sentence.size(); i++) {
String[] matchArray = new String[sentence.get(i).split(" ").length];
for (int j = 0; j < keyword.size(); j++) {
if (sentence.get(i).contains(keyword.get(j))) {
matchArray[Arrays.asList(sentence.get(i).split(" ")).indexOf(keyword.get(j))] = keyword.get(j);
}
}
List<String> matchList = new ArrayList<String>();
for(String match: matchArray) {
if(match != null) {
matchList.add(match);
}
}
System.out.println(matchList);
}
For every sentence create an array with size same as the sentence (just to ensure size). Now when matches are found get the index of the match from sentence and add element to that particular index of the array. So at the end of keyword iteration you will have all matches in array with null values if some words are not matching.
Now declare a new List of String into which add the elements from array which are not null. At last print the list.
I think Map would be a good choice here. Just make sentences keys for the map and keywords as value. Following is the code for the same.
Map <String, ArrayList<String>> sentences= new HashMap<>();
sentences.put("this is a good dog", new ArrayList<>());
sentences.put("cats drink milk", new ArrayList<>());
sentences.put("Animals are beautiful creatures", new ArrayList<>());
List <String> keyword= new ArrayList <>();
keyword.add("dog");
keyword.add("cats");
keyword.add("beautiful");
keyword.add("good");
keyword.add("are");
keyword.add("this");
keyword.add("milk");
keyword.forEach(word -> sentences.entrySet().stream()
.filter(map -> map.getKey().contains(word)).
forEach(map -> sentences.computeIfAbsent(map.getKey(), key->new ArrayList<>()).add(word)));
sentences.forEach((key, value) -> System.out.println(value));
Try something like this:
for (String sen: sentence) {
System.out.print("[");
boolean first = true;
for (String word: sen.split("[\\s\\p{Punct}]")) {
if (keyword.contains(word)) {
if (first) {
first = false;
} else {
System.out.print(",");
}
System.out.print(word);
}
}
System.out.println("]");
}
this should do it, printing exactly in the format you requested :
for (int b = 0; b < sentence.size(); b++) {
String arr[] = sentence.get(b).split("\\s+");
List result = new ArrayList<>();
for (int c = 0; c < arr.length; c++ ) {
if (keyword.contains(arr[c]))
result.add(arr[c]);
}
System.out.println(result);
}
I would use the following :
for(String currentSentence : sentence) {
List<String> keywordsInSentence = new ArrayList<>();
for (String word : currentSentence.split("\\s+")) {
if (keyword.contains(word)) {
keywordsInSentence.add(word);
}
}
System.out.println(keywordsInSentence);
}
You can try it here.
(and I'd rename sentence into sentences or sentenceList and similarly for keyword, otherwise it's just confusing)
If you need to do anything more to the keywords than immediately displaying them, you could insert the keywordsInSentence lists into a Map<String, List<String>> you would value by replacing the System.out.println by map.put(currentSentence, keywordsInSentence).

How to find permutations for String arrays excluding own array?

I have the following bunch of arrays:
public class ArrayPermutationExample {
private static final String PREFIX = "ignore(FAILURE) { build(\"load\", ";
public static final String ENDING = ")}";
private static String[] arr_1 = new String[] {
"111",
"222",
"333"};
private static String[] arr_2 = new String[]{
"aaa",
"bbb",
"ccc"};
private static String[] arr_3 = new String[] {
"***",
"&&&",
"$$$"};
I need to find permutation with other arrays, excluding native array.
The output should look like:
111aaa
111bbb
111ccc
111***
111&&&
111$$$
222aaa
222bbb
222ccc
...
333aaa
333bbb
333ccc
...
Finally, for all those permutations should be added prefix and ending:
prefix permutation string endings
And at the end we should have something like:
ignore(FAILURE) { build("load", 111aaa )}
I completely stuck with a solution for this task:
private static void processArrays(String[] ... arrays) {
ArrayList<String> result = new ArrayList<>();
for (String[] array : arrays) {
String[] currentArray = array;
for (String line : currentArray) {
// exclude all lines from current array & make concatenation with every line from others
}
}
}
How to solve this issue?
UPDATE:
I want to add that finally, we need to have a distinct list without any dublications. Even following example will be duplicating each other:
111aaa***
***111aaa
I believe that this task should have a solution with Java 8 style.
I think this may be a combination since you don't actually care about getting all orderings (other than printing in the order specified by the order of the array parameters), but regardless, here is the code I wrote. I used a stack for storing unfinished arrays. Pushing to the stack each possibility at any given point for every array and pushing to results for any completed array.
public static List<String> getCombinations(String prefix, String ending, String[]... arrays) {
List<String> results = new ArrayList<>();
Stack<String[]> combinations = new Stack<>();
combinations.add(new String[arrays.length]);
while (!combinations.isEmpty()) {
String[] currentArray = combinations.pop();
if (currentArray[arrays.length - 1] == null) {
for (int i = 0; i < arrays.length; i++) {
if (currentArray[i] == null) {
for (int j = 0; j < arrays[i].length; j++) {
String[] newArray = currentArray.clone();
newArray[i] = arrays[i][j];
combinations.add(newArray);
}
break;
}
}
} else {
StringBuilder stringBuilder = new StringBuilder(prefix);
for (String string : currentArray) {
stringBuilder.append(string);
}
stringBuilder.append(ending);
results.add(stringBuilder.toString());
}
}
return results;
}
You would just need to iterate over the returned list to print out all of the strings.
As an added note, this method could be written recursively, but I usually like using a stack instead of using recursion when possible because recursion can be slow sometimes.
The way I read it: the first array arr_1 is prepended to the next 3 arrays.
I think the prefix is "ignore(FAILURE) { build("load", " and the ending is "}}"
String prefix = "ignore(FAILURE) { build(\"load\", ";
String ending = "}}";
for (String first: arr_1) {
for (String second: arr_2) {
System.out.println( prefix + first + second + ending);
}
for (String second: arr_3) {
System.out.println( prefix + first + second + ending);
}
for (String second: arr_4) {
System.out.println( prefix + first + second + ending);
}
}

Java : Compare previous record with current record in arraylist

I have a sorted array list with 6 elements.The first 5 elements have some value, and the 6th one is empty.
I want to loop through this ArrayList, and compare the first 5 elements of first record, with the same elements in next record. If any one of the element is different, then populate 6th element.
Anyone know an easier and faster approach to do that?
Thanks
Angad
First split the all records into many String[], then parse all values in each. After that you can compare the current record with the first one. Here is an example:
public class StringComparison {
ArrayList<String[]> list = new ArrayList<String[]>();
public void comapreStrings() {
// The list you are comparing everything to
String[] firstRecord = list.get(0);
for(int n = 1; n < list.size(); n++) {
String[] currentRecord = list.get(n);
for (int i = 0; i < currentRecord.length; i++) {
String val1 = firstRecord[i];
String val2 = currentRecord[i];
if (val1.equals(val2)) {
// The two strings are the same
} else {
// Replace "a value" with whatever you want to fill the 6th element with
currentRecord[5] = "a value";
}
}
}
}
Maybe this could be an alternative to think about:
public String[] generateFirstRow(int startingRow) {
final String[] row1 = rowList.get(startingRow);
final String[] row2 = rowList.get(startingRow + 1);
final List<String> list1 = Arrays.stream(row1).collect(toList());
final List<String> toAdd = Arrays.stream(row2).parallel().sorted().filter(s -> !list1.contains(s)).collect(Collectors.toList());
if (list1.get(list1.size() - 1) == "") {
list1.set(list1.size() - 1, toAdd.get(0));
return list1.toArray(new String[0]);
}
return new String[0];
}
Now you can call this per row you have untill the pre-last one.

Merging values of 2 string arrays in one concatenated strings array

I have 2 string arrays.
string [] first = {"ajunkbc","ajunkHello","adedbc","abcjunk","add","ad","a","","junk","ajunk","aajunkbb"};
String [] second = {"abc","aHello","adedbc","abcjunk","add","ad","a","","junk","a","aajunkbb"};
I'd like the result of my merge() method to concatenate each element from the first array with the respective element of the second array separated by a comma.
Below is my code
private static String[] merge(String [] tests, String [] expectations){
List<String> testList = Arrays.asList(tests);
List<String> expectationsList = Arrays.asList(expectations);
List<String> retList = new ArrayList<String>();
for(String test : testList){
for(String val : expectationsList){
retList.add(test+","+val);
break;
}
}
This does not work. What's wrong with my code?
What's wrong is that you are looping over expectationsList and breaking out of the loop after the first iteration:
for(String val : expectationsList){
retList.add(test+","+val);
break; //<--- breaking out of loop after first iteration each time
}
So the result is that you are always retrieving the first element of expectationsList.
Since what you want is to loop over two arrays, you should use an index:
for (int i = 0; i < testList.size(); i++) {
retList.add(testList.get(i)+","+expectationsList.get(i));
}
Also, note that this implies that the size of testList is the same as the size of expectationsList. Your method should probably throw an exception if this is not the case.
Note that you do not need to convert the input arrays into lists. You can use them as-is.
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
String[] result = new String[tests.length];
for (int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i]);
}
return result;
}
Java 8 solution:
private static String[] merge(String[] tests, String[] expectations) {
if (tests.length != expectations.length) {
throw new IllegalArgumentException("input not of same length");
}
return IntStream.range(0, tests.length).mapToObj(i -> tests[i] + "," + expectations[i]).toArray(String[]::new);
}
You're iterating through each member of testList and then for each one, iterating through each member of expectationsList. You want to iterate through each of both of them together.
What you want to do is something like this:
private static String[] merge(String[] tests, String[] expectations) {
String[] result = new String[tests.length];
for(int i = 0; i < tests.length; i++) {
result[i] = tests[i] + "," + expectations[i];
}
return result;
}
This code makes the assumption that tests and expectations have the same length. You might want to do a check for that at the beginning:
if (tests.length != expectations.length) {
throw new IllegalArgumentException("tests and expectations are of different lengths")
}
Notice how now you're getting the element at the same index from both arrays.
Sidenote: You can iterate over arrays with the for each format. This works just fine:
String[] myStringArray = getStringArray();
for (String myString : myStringArray) {
// Do something
}
You don't need to convert to a List in order to iterate :)

printing elements of array in arraylist in java

I do have this code, and I would like to print out all the array's values of Arraylist.
thanks for your help in advanced.
here is my code:
for (int i = 0; i <count; i++) {
System.out.println("list #" + i);
for (int j = 0; j < list[i].size(); j++) {
list[i].get(j);
System.out.println("elements of array in arraylist "+list[i].get(j));
}
}
For printing elements of an array stored in arraylist,you will have to to do the following:
for each element of arraylist
get array from arraylist
for each array element in array
print array element.
You seemed to be iterating array of List type instead.
Edit your code with further detail on your data structure
for (Object[] array : list)
for (Object o : array)
System.out.println("item: " + o);
See if this can work for you. I think it's simpler:
int numLists = 10; // Or whatever number you need it to be.
ArrayList [] arrayOfLists = new ArrayList[numLists];
// you realize, of course, that you have to create and add those lists to the array.
for (ArrayList list : arrayOfLists) {
System.out.println(list);
}
I'd wonder why you don't prefer a List of Lists:
List<List<String>> listOfLists = new ArrayList<List<String>>();
// add some lists of Strings
for (List<String> list : listOfLists) {
System.out.println(list);
}
Below code works fine for me
public class Solution
{
public static void main(String[] args)
{
int T,N,i,j,k=0,Element_to_be_added_to_the_array;
Scanner sn=new Scanner(System.in);
T=sn.nextInt();
ArrayList<Integer>[] arr=new ArrayList[T];
for(i=0;i<T;i++)
{
arr[k]=new ArrayList<Integer>();
N=sn.nextInt();
for(j=0;j<N;j++)
{
Element_to_be_added_to_the_array=sn.nextInt();
arr[k].add(Element_to_be_added_to_the_array);
}
k++;
}
//Printing elements of all the arrays contained within an arraylist
for(i=0;i<T;i++)
{
System.out.println("array["+i+"]");
for(j=0;j<arr[i].size();j++)
{
System.out.println(arr[i].get(j));
}
}
}
}

Categories