I want to convert lists of lists into two separate string arrays.
I want to convert taglist into string array TagArray[] and tokenlist into array called TokenArray.
I tried many ways but there are many ways to convert Converting an ArrayList into a 2D Array but I cannot find any method to convert Lists of lists to String array. Can anyone help me to do this.
taglist
[[NON, NON], [NON, NON ], [NON, NON, NON], [NON, NON] ,[ENTITY, ENTITY]]
tokenlist
[[John, ran], [John, jumped], [The, dog, jumped], [Mary, sat], [Finland, India]]
I tried the following way
for(int i=0;i<tokenlist.size();i++)
{
String[] words = tokenlist.get(i);
}
I am getting the output when i use above way. but the problem is that i have to take i th value from tokenlist and taglist at the same time
OR
I have to convert this into 3 D array which has the following format
static final String[][][] WORDS_TAGS = new String[][][]
{
{ { "John", "ran" }, { "NON", "NON" } },
{ { "John", "jumped"}, { "NON", "NON "} },
{ { "The", "dog", "jumped"}, { "NON", "NON", "NON" } },
{ { "Mary", "sat"}, { "NON", "NON"} },
{ { "Finland","India" }, { "ENTITY","ENTITY" } },
};
try this
List<List<String>> l1 = Arrays.asList(Arrays.asList("NON", "NON"),
Arrays.asList("NON", "NON"),
Arrays.asList("NON", "NON", "NON"),
Arrays.asList("NON", "NON"), Arrays.asList("ENTITY", "ENTITY"));
List<List<String>> l2 = Arrays
.asList(Arrays.asList("John", "ran"),
Arrays.asList("John", "jumped"),
Arrays.asList("The", "dog", "jumped"),
Arrays.asList("Mary", "sat"),
Arrays.asList("Finland", "India"));
String[][][] a = new String[l1.size()][][];
for (int i = 0; i < l1.size(); i++) {
a[i] = new String[][] {
l2.get(i).toArray(new String[l2.get(i).size()]),
l1.get(i).toArray(new String[l1.get(i).size()]) };
}
System.out.println(Arrays.deepToString(a));
output
[[[John, ran], [NON, NON]], [[John, jumped], [NON, NON]], [[The, dog, jumped], [NON, NON, NON]], [[Mary, sat], [NON, NON]], [[Finland, India], [ENTITY, ENTITY]]]
String[] words = new String[20];
int index = 0;
for(int i=0;i<L2.size();i++)
{
List l5 = (List)L2.get(i);
for(int j=0;j<l5.size();j++){
words[index] = (String)l5.get(j);
index++;
}
}
you need two for loop. one for external and another for internal
Try this
String[][][] newArray = new String[taglist.size()][2][];
for(int i=0;i<taglist.size();i++){
String[] arr=tokenlist.get(i).toArray(new String[tokenlist.get(i).size()]);
newArray[i][0]= arr;
arr= taglist.get(i).toArray(new String[taglist.get(i).size()]);
newArray[i][1]= arr;
}
Related
This question already has answers here:
Merge two arrays and remove duplicates in Java
(7 answers)
Closed 1 year ago.
I was able to get the two arrays to sort and merge but I can not figure out how to remove the duplicates. Can someone please help me with this? Here is my code so far:
public class FinalArray {
public static void main(String[] args) {
String[] testArray1 = {"coffee", "tea", "water"};
String[] testArray2 = {"lemonade", "juice", "water"};
mergeUniqueValues(testArray1, testArray2);
}
public static void mergeUniqueValues(String[] arr1, String[] arr2) {
String[] arr3 = new String[arr1.length + arr2.length];
for (int i = 0; i < arr1.length; i++) {
arr3[i] = arr1[i];
}
for (int i = arr1.length, index = 0; i < arr1.length + arr2.length; i++, index++) {
arr3[i] = arr2[index];
}
Arrays.sort(arr3);
System.out.println("Your sorted array is: ");
for (String str : arr3) {
System.out.println(str);
}
}
}
Property of Set: It does not allow duplicates.
You can simply convert the array to Set (to avoid duplicates) and then convert it back to an array.
Here is a sample code for your reference:
public class Main {
public static void main(String[] args) {
String[] testArray1 = {"coffee", "tea", "water"};
String[] testArray2 = {"lemonade", "juice", "water"};
mergeUniqueValues(testArray1, testArray2);
}
public static void mergeUniqueValues(String[] arr1, String[] arr2) {
Set noDuplicateSet = new HashSet();
noDuplicateSet.addAll(Arrays.asList(arr1));
noDuplicateSet.addAll(Arrays.asList(arr2));
String[] noDuplicateArray = new String[noDuplicateSet.size()];
noDuplicateSet.toArray(noDuplicateArray);
Arrays.sort(noDuplicateArray);
System.out.println("Your sorted array is: ");
for (String str : noDuplicateArray) {
System.out.println(str);
}
}
}
Output:
Your sorted array is:
coffee
juice
lemonade
tea
water
You can use Java Streams and distinct().
String[] result =
Stream.concat( // combine
Stream.of(array1),
Stream.of(array1))
.distinct() // filter duplicates
.sorted() // sort
.toArray(String[]::new);
You can take advantage from the java.util.TreeSet class, which is a collection which implements java.util.Set, and made of all unique values ordered by the natural order of the given elements. In your case, String does implement Comparable, so it can be naturally ordered when the element are inserted in the collection.
Here is the code you can test:
import java.util.*;
public class MergeArray {
public static void main(String[] args) {
String[] testArray1 = { "coffee", "tea", "water" };
String[] testArray2 = { "lemonade", "juice", "water" };
mergeUniqueValues(testArray1, testArray2);
}
public static void mergeUniqueValues(String[] arr1, String[] arr2) {
Set<String> mergedList = new TreeSet(Arrays.asList(arr1));
mergedList.addAll(Arrays.asList(arr2));
String[] arr3 = mergedList.toArray(String[]::new);
System.out.println("Your sorted array is: ");
for (String str : arr3) {
System.out.println(str);
}
}
}
And here is the output:
Your sorted array is:
coffee
juice
lemonade
tea
water
You can use Java Stream:
String[] testArray1 = {"coffee", "tea", "water"};
String[] testArray2 = {"lemonade", "juice", "water"};
String[] testArray3 = Stream.of(testArray1, testArray2)
.flatMap(Arrays::stream).distinct().sorted().toArray(String[]::new);
Arrays.stream(testArray3).forEach(System.out::println);
//coffee
//juice
//lemonade
//tea
//water
I am trying to store data from ArrayList to Strings until a symbol shows up. So for example, there is an ArrayList with the following Items:
{Start, at , - , Bob, amazing, gold, -, Peter, pan, Bright, shine, - , Sugar, shack -, lol, -}
I put random names for demonstration, but anywho I am trying to store data in a String until it sees a symbol.
So For the above list, data will be stored in multiple strings in the following way:
String first = "Start at"
String second = "Bob amazing gold"
String third = "Peter pan bright shine"
String forth = "Sugar shack"
String fifth = "lol"
The above list is just an example. I am trying to implement a code that works with any list. So there is no pattern. The code should keep strong data to a String until it sees a symbol. Any ideas on how I can accomplish this? Please let me know!
You can iterate through each element of your list and chain the strings which doesn't contain symbols. Then you could store your result in a List.
public static void main(String[] args) {
List<String> wordList = Arrays.asList("Start", "at", "-", "Bob", "amazing", "gold", "-", "Peter", "pan", "Bright", "shine", "-", "Sugar", "shack", " -", "lol", "-");
List<String> result = new ArrayList<>();
StringBuilder builder = new StringBuilder();
for (String word : wordList) {
if (isSymbol(word)) {
result.add(builder.toString());
builder = new StringBuilder();
} else {
if (builder.length() != 0) {
builder.append(' ');
}
builder.append(word);
}
}
if (builder.length() > 0) {
result.add(builder.toString());
}
System.out.println(result);
}
public static boolean isSymbol(String name) {
return name.matches("[ -]+");
}
May be simpler:
public static void main(String[] args) {
List<String> wordList = Arrays.asList("Start", "at", "-", "Bob", "amazing", "gold", "-", "Peter", "pan", "Bright", "shine", "-", "Sugar", "shack", " -", "lol", "-");
List<String> result = new ArrayList<>();
StringBuilder builder = new StringBuilder();
for (String word : wordList) {
builder.append(word).append(" ");
}
String[] splits = builder.toString().split(" -");
result.addAll(Arrays.asList(splits));
System.out.println(result);
}
So I am trying to create small Java program where names from array are paired. But I don't know how to proceed. I have array with names and the object is to pair two names randomly to make a team. There should be some statement so certain pairs couldn't be made: Miller & James can't be in the same team and no dublicates. How do I do this?
Example output:
James & Hal
import java.util.Random;
public class Teams {
public static void main (String [] args) {
String [] arr = {"John", "James", "George", "Miller", "Hal", "Dan"};
Random random = new Random();
int select = random.nextInt(arr.length);
int selectSecond = random.nextInt(arr.length);
System.out.println(arr[select]);
System.out.println(arr[selectSecond]);
}
}
You can delete the first chosen name from the array and then choose again to get the second one. To delete an element from an array see Removing an element from an Array (Java). Here is one possible implementation (but I didn't test it):
public static void main (String [] args) {
String [] arr = {"John", "James", "George", "Miller", "Hal", "Dan"};
Random random = new Random();
int select = random.nextInt(arr.length);
arr = removeElements(arr, arr[select]);
int selectSecond = random.nextInt(arr.length);
System.out.println(arr[select]);
System.out.println(arr[selectSecond]);
}
// import java.util.LinkedList;
public static String[] removeElements(String[] input, String deleteMe) {
List result = new LinkedList();
for(String item : input)
if(!deleteMe.equals(item))
result.add(item);
return (String[]) result.toArray(input);
}
I would like to use Collections.shuffle instead, and a do while loop like so :
String[] arr = {"John", "James", "George", "Miller", "Hal", "Dan"};
List<String> list = Arrays.asList(arr);
String name1, name2;
do {
Collections.shuffle(list);
name1 = list.get(0);
name2 = list.get(1);
} while ((name2.equals("Miller") && name1.equals("James"))
|| (name1.equals("James") && name2.equals("Miller")));
System.out.println(String.format("%s & %s", name1, name2));
With this solution you don't need to check if the both names are same or not, you just need to check if the two name not equals in the same pair to Miller and James
It will depend which perspective you want to attack here. If you just want to "do the job", you have an extensive list of possibilities (as we already have here), but I would just take care with readability:
public class Teams {
private static String[][] teamsToAvoid = {{"James", "Miller"}, {"John", "Hal"}};
private static String[][] teamsFormed = new String[3][2];
public static void main(String[] args){
String[] names = {"John", "James", "George", "Miller", "Hal", "Dan"};
List<String> namesList = new ArrayList<>(Arrays.asList(names));
Collections.shuffle(namesList);
do {
formTeam(namesList, 0, 1);
} while(namesList != null && !namesList.isEmpty());
for(String[] team : teamsFormed){
System.out.println("Team: {" + team[0] + ", " + team[1] + "}");
}
}
private static void formTeam(List<String> namesList, int firstPlayerIndex, int secondPlayerIndex) {
if(isTeamPossible(namesList.get(firstPlayerIndex), namesList.get(secondPlayerIndex))){
String firstPlayer = namesList.get(firstPlayerIndex);
String secondPlayer = namesList.get(secondPlayerIndex);
teamsFormed[getFormedTeamNextIndex()] = new String[]{firstPlayer, secondPlayer};
namesList.remove(namesList.indexOf(firstPlayer));
namesList.remove(namesList.indexOf(secondPlayer));
} else {
formTeam(namesList, firstPlayerIndex, ++secondPlayerIndex);
}
}
private static boolean isTeamPossible(String player1, String player2) {
for(String[] teamToAvoid : teamsToAvoid){
if(Arrays.asList(teamToAvoid).contains(player1) && Arrays.asList(teamToAvoid).contains(player2)){
return false;
}
}
return true;
}
private static int getFormedTeamNextIndex() {
for(int i = 0; i < teamsFormed.length; i++){
if(teamsFormed[i][0] == null && teamsFormed[i][1] == null)
return i;
}
return 0;
}
}
Doing this you will prevent the same pair in different order and remove those players from the list (preventing their reuse).
I would pay attention when removing from list directly by index also, because when you remove one item the index for items after that one change.
I had a string dataset as follows:
row 1: "abc', "def", "ghi"
row 2: "xyz"
row 3: "lmn", "opq", "rst", "uvw"
For the start I would like to loop over each row and column and output the values in a window.
I was not sure of how to do this since, each row has different number of columns.
Could someone please tell me what would be the best way to initialize this dataset in java?
Thanks
Regards
Option 1:
List<String[]> dataSet = new ArrayList<String[]>();
dataSet.add(new String[] { "abc", "def", "ghi" });
dataSet.add(new String[] { "xyz" });
dataSet.add(new String[] { "lmn", "opq", "rst", "uvw" });
Option 2:
If you know the number of rows in advance, you can also do this:
int numRows = 3; //if you know the number of rows in advance
String[][] dataSet2 = new String[numRows][];
dataSet2[0] = new String[] { "abc", "def", "ghi" };
dataSet2[1] = new String[] { "xyz" };
dataSet2[2] = new String[] { "lmn", "opq", "rst", "uvw" };
First you need to decide how to parse your strings, are they different 1D arrays or all in a 2D array? You could make a 2D array length the size of the largest array and test for nulls in the shorter ones... your simple loop would look something like this:
<code>
for (int i=0; i < 3; i++) {
for (int j=0; j< currentArray.length && currentArray[j] != NULL; j++) {
System.out.println(currentArray[i][j]);
}
}
</code>
How can we access to a multiple dimension array without even knowing it !
For example :
Object[][] inputs = { new Object[] { "a", "ab", "abc" },
new Object[] { "abc", "ab", "a" },
new Object[] { "big", new Object[] { "ab", "a", }, "t" },
new Object[] { "big", new Object[] { "ab", "a", new Object[] { "superbig", "a" } }, "tiny" },
new Object[] { 123, 23123123, "a" },
new Object[] { null, new Object[] {}, "a" } };
I thought it was 2 dimensional but it's not 2 (which i'm not happy with that syntax of java) and i need to get all the information of the inputs array object.
How am i suppose to solve this ? Is there any method for transforming a multidimensional array into one dimension ?
P.S.: The Output should be { abc, abc, big,superbig,23123123,a} (it's the biggest string of each line of the object !)
You can easily flatten any-dimensional array to single dimension, at runtime, using reflection. You can use it to compute find longest strings as you required with your edit.
Working runnable example program:
import java.lang.reflect.*;
import java.util.*;
public class Program {
private static Object[] toSingleDimension(Object array) {
ArrayList<Object> arrayList = new ArrayList<>();
toSingleDimensionRecursive(arrayList, array);
return arrayList.toArray();
}
private static void toSingleDimensionRecursive(ArrayList<Object> output, Object object) {
if (object == null) {
output.add(null);
} else if (!object.getClass().isArray()) {
output.add(object);
} else {
int length = Array.getLength(object);
for (int i = 0; i < length; ++i) {
Object value = Array.get(object, i);
toSingleDimensionRecursive(output, value);
}
}
}
private static String findLongestString(Object[] array) {
if (array == null) {
return null;
}
String result = null;
for (Object object : array) {
if (object != null) {
String text = object.toString();
if (result == null) {
result = text;
} else if (text != null && text.length() > result.length()) {
result = text;
}
}
}
return result;
}
public static void main(String[] args) {
Object[][] inputs = {new Object[]{"a", "ab", "abc"},
new Object[]{"abc", "ab", "a"},
new Object[]{"big", new Object[]{"ab", "a",}, "t"},
new Object[]{"big", new Object[]{"ab", "a", new Object[]{"superbig", "a"}}, "tiny"},
new Object[]{123, 23123123, "a"},
new Object[]{null, new Object[]{}, "a"}};
// Object[] data = toSingleDimension(inputs);
// System.out.println(Arrays.asList(data));
ArrayList<String> longestStrings = new ArrayList<>();
for (Object input : inputs) {
Object[] array = toSingleDimension(input);
String longest = findLongestString(array);
if (longest != null) {
longestStrings.add(longest);
}
}
System.out.println("Longest strings of arrays: " + longestStrings);
}
}
Outputs:
Longest strings of arrays: [abc, abc, big, superbig, 23123123, a]
You can use recursion to achieve this easily.
public List<Object> convert(Object input) {
List<Object> objectList = new ArrayList<>();
if (input instanceof Object[]) {
for (Object object : (Object[]) input) {
objectList.addAll(convert(object)); // Instead of addAll here, just add max element. I am a little too lazy to implement that...:)
}
} else {
objectList.add(input);
}
return objectList;
}