Transform Set<Keyword> into String[] - java

I have an object Keyword that stores a String with the text of the keyword and a set o keywords (Set<Keyword>) that I need to transform into a String array. Is there a quick/easy way to do this or I need to iterate the set and add each keyword one by one?
EDIT:
For those asking for Keyword class:
#Entity
public class Keyword {
// ...
#Basic
private String value;
// ...
// Getters & Setters
}

Every class that implements Collection intefrace (and that includes Set) has toArray() method:
String[] array= set.toArray(new String[0]);
In case of a set that is parametrized with some other type, e.g. Set<Keyword> you would have to do something like:
Keyword[] array= set.toArray(new Keyword[0]);
String[] stringArray= new String[array.length];
for (int i=0; i<array.length; i++) {
stringArray[i]= array[i].getThatString();
}

Try this:
String[] arr = set.toArray(new String[set.size()]);
... is what I would have said, if you had a Set<Object>.
No, there is no way to directly convert a Set<Keyword> to a String[] since there is no direct relationship between Keyword and String. You will have to iterate over the set:
String[] arr = new String[set.size()];
int i = 0;
for (Keyword word : set)
arr[i++] = word.toString();

If you use Guava, you may use this:
Lists.transform(Lists.newArrayList(theSet), Functions.usingToString())
.toArray(new String[theSet.size()])
And this only scratches the surface of what Guava can actually do.

There is no specific way to do this . You can either convert Set to Object[] using set.toArray and then iterate over the array
or
iterate over the set directly

You may need to add toString() method to your Keyword class as shown below. Or you can use a separate transformer class/method.
class Keyword {
private String value;
Keyword(String v) {
this.value = v;
}
public String toString() {
return value;
}
}
.
I would say iterate the set and add each keyword one by one is your best possible strategy.
System.out.println(toStringArray(set));
.
private static String[] toStringArray(Collection<?> set) {
String[] arr = null;
if (set != null) {
arr = new String[set.size()];
int i = 0;
for (Object o : set) {
arr[i++] = o.toString();
}
}
return arr;
}
.
However if you really want, you can have a dirty workaround as shown below. Only issue here is that your keyword value cannot contain comma (,) as it is used by split() method.
String str = set.toString();
str = str.substring(1, str.length() - 1);
String[] asStringArray = str.split(",");
System.out.println(asStringArray);

Related

Converting array list to a string array

I've been trying to convert my string array list to a string array so I can print it but have been unable to do so.
This is the class I have, randomQuestion which takes in an array list from the gameQuestions method in the same class.
I have never tried to convert an array list using a loop before hence the difficulty, I was able to convert it fine with the code
String[] questions = data1.toArray(new String[]{});
But I need it to loop through using a for loop to store it in an array which I can then print one at a time once a question is answered successfully.
The error I'm receiving from netbeans is cannot find symbol
Symbol:methodtoArray(String[]) for the .toArray portion below.
public String[] randomQuestion(ArrayList data1) {
Collections.shuffle(data1);
for (int question = 0; question < 10; question++) {
ranquestions = data1.get(question).toArray(new String[10]);
}
return ranquestions;
}
Any help would be greatly appreciated.
You can use List.toArray(). Class List has a method:
<T> T[] toArray(T[] a);
Assuming you have an ArrayList<String>, you can use String.join(delimiter, wordList) in order to concatenate all the elements to a single String:
public static void main(String[] args) {
// example list
List<String> words = new ArrayList<String>();
words.add("You");
words.add("can");
words.add("concatenate");
words.add("these");
words.add("Strings");
words.add("in");
words.add("one");
words.add("line");
// concatenate the elements delimited by a whitespace
String sentence = String.join(" ", words);
// print the result
System.out.println(sentence);
}
The result of this example is
You can concatenate these Strings in one line
So using your list, String.join(" ", data1) would create a String with the elements of data1 delimited by a whitespace.
The question is how to create an array with only 10 elements of the list, if I understood correctly.
Streams (Java 8):
String[] ranquestions = data1.stream()
.limit(10)
.toArray(String[]::new);
Loop (based on question, avoiding unnecessary changes):
String[] ranquestions = new String[10];
for(int question = 0; question < 10; question++) {
ranquestions[question] = data1.get(question);
}
always assuming List<String> data1, if not some conversion is needed.
Example:
String[] ranquestions = data1.stream()
.limit(10)
.map(String::valueOf)
.toArray(String[]::new);
or, loop case:
ranquestions[question] = String.valueOf(data1.get(question));
You can do:
private String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
If you are sure you are getting a list of string (question) you can instead
private String[] randomQuestions(List<String> data){
Collections.shuffle(data);
return (String[]) data.toArray();
}
Edit 1
private static String[] randomQuestions(ArrayList data){
Collections.shuffle(data);
String[] randomQuestions = new String[data.size()];
for(int i=0; i<data.size(); i++){
randomQuestions[i] = String.valueOf(data.get(i));
}
return randomQuestions;
}

Remove elements from ArrayList after finding element with specific char

I have an ArrayList that contains a number of Strings, I want to be able to iterate through the ArrayLists contents searching for a string containing a semicolon. When the semicolon is found I then want to delete all of the Strings including and after the semicolon string.
So;
this, is, an, arra;ylist, string
Would become:
this, is, an
I feel like this is a very simple thing to do but for some reason (probably tiredness) I can't figure out how to do it.
Here's my code so far
public String[] removeComments(String[] lineComponents)
{
ArrayList<String> list = new ArrayList<String>(Arrays.asList(lineComponents));
int index = 0;
int listLength = list.size();
for(String str : list)
{
if(str.contains(";"))
{
}
index++;
}
return lineComponents;
}
This becomes trivial with Java 9:
public String[] removeComments(String[] lineComponents) {
return Arrays.stream(lineComponents)
.takeWhile(s -> !s.contains(";"))
.toArray(String[]::new);
}
We simply form a Stream<String> from your String[] lineComponents and take elements until we find a semicolon. It automatically excludes the element with the semicolon and everything after it. Finally, we collect it to a String[].
First of all I think you are confusing arrays and arraylists. String[] is an array of strings while ArrayList<String> is an arraylist of strings. Take into account that those are not the same and you should read Array and ArrayList documentation if needed.
Then, to solve your problem following the ArrayList approach you can go as follows. Probably it's not the optimum way to do it but it will work.
public List<String> removeComments(List<String> lineComponents, CharSequence finding)
{
ArrayList<String> aux = new ArrayList<String>();
for(String str : lineComponents)
{
if(str.contains(finding))
break;
else
aux.add(str);
}
return aux;
}
This example is just for performance and bringing back my old favorite arraycopy:
public String[] removeComments(String[] lineComponents) {
int index = -1;
for (int i = 0; i < lineComponents.length; i++) {
if ( lineComponents[i].contains(";") ) {
index = i;
break;
}
}
if (index == -1) return lineComponents;
return Arrays.copyOf(lineComponents, index);
}

Java split string from array

I have a string array that contains some information.
Example:
String [] testStringArray;
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
This is exactly how the information is. Now my problem is I want to make each element a seperate element in an array and I want to split it based on the \n character.
So I want
newArray[0]=Jim,35
newArray[1]=Alex,45
newArray[2]=Mark,21
newArray[3]=Ana,18
etc etc. I am aware of the split method but won't this just split each array element into a completely new array instead of combining them?
If anyone could help, it would be appreciated. Thanks
Something like this:
// Splits the given array of Strings on the given regex and returns
// the result in a single array.
public static String[] splitContent(String regex, String... input) {
List<String> list = new ArrayList<>();
for (String str : input) {
for (String split : str.split(regex)) {
list.add(split);
}
}
return list.toArray(new String[list.size()]);
}
you can call it this way:
String[] testStringArray = ...;
String[] newArray = splitContent("\n", testStringArray);
Because of the use of varargs you can also call it like this:
String[] newArray = splitContent("\n", str1, str2, str3, str4);
where strX are String variables. You can use any amount you want. So either pass an array of Strings, or any amount of Strings you like.
If you don't need the old array anymore, you can also use it like this:
String[] yourArray = ...;
yourArray = splitContent("\n", yourArray);
String[] testStringArray = new String[2];
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21";
testStringArray[1]= "Jiam,35\nAleax,45\nMarak,21";
for(String s : testStringArray) {
String[] temp = s.split("\n");
for(String t : temp) {
result.add(t);
}
}
String[] res = result.toArray(new String[result.size()]);
Try This is working Code >>
String[] testStringArray = new String[2]; // size of array
ArrayList<String> result = new ArrayList<String>();
testStringArray[0]= "Jim,35\nAlex,45\nMark,21"; // store value
testStringArray[1]= "Ana,18\nMegan,44";
for(String s : testStringArray) {
String[] temp = s.split("\n"); // split from \n
for(String t : temp) {
result.add(t); // add value in result
System.out.print(t);
}
}
result.toArray(new String[result.size()]);
you can first merge the strings into one string and then use the split method for the merged string.
testStringArray[0]= Jim,35
Alex,45
Mark,21
testStringArray[1]= Ana,18
Megan,44
StringBuffer sb = new StringBuffer();
for(String s : testStringArray){
s = s.trim();
sb.append(s);
if (!s.endWith("\n")){
sb.append("\n");
}
}
String[] array = sb.toString().split("\n");
Try this. It is simple and readable.
ArrayList<String> newArray = new ArrayList<String>();
for (String s : testStringArray) {
newArray.addAll(Arrays.asList(s.split("\\n"));
}
Firstly, you can't write what you just did. You made a String array, which can only contain Strings. Furthermore the String has to be in markers "" like "some text here".
Furthermore, there can only be ONE String at one place in the array like:
newArray[0] = "Jim";
newArray[1] = "Alex";
And NOT like:
newArray[0] = Jim;
And CERTAINLY NOT like:
// Here you're trying to put 2 things in 1 place in the array-index
newArray[0] = Jim, 35;
If you wan't to combine 2 things, like an name and age you have to use 2D array - or probably better in your case ArrayList.
Make a new class with following object:
public class Person {
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
And afterwards go to your class where you want to use the original array, and write:
ArrayList<Person> someNameOfTheArrayList = new ArrayList<Person>();
someNameOfTheArrayList.add(new Person("Jim", 32));
someNameOfTheArrayList.add(new Person("Alex", 22));

Print ArrayList

I have an ArrayList that contains Address objects.
How do I print the values of this ArrayList, meaning I am printing out the contents of the Array, in this case numbers.
I can only get it to print out the actual memory address of the array with this code:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i));
}
list.toString() is good enough.
The interface List does not define a contract for toString(), but the AbstractCollection base class provides a useful implementation that ArrayList inherits.
Add toString() method to your address class then do
System.out.println(Arrays.toString(houseAddress));
From what I understand you are trying to print an ArrayList of arrays and one way to display that would be
System.out.println(Arrays.deepToString(list.toArray()));
since you haven't provide a custom implementation for toString() method it calls the default on which is going to print the address in memory for that object
solution
in your Address class override the toString() method like this
public class Address {
int addressNo ;
....
....
...
protected String toString(){
return Integer.toString(addressNo);
}
now when you call
houseAddress.get(i) in the `System.out.print()` method like this
System.out.print( houseAddress.get(i) ) the toString() of the Address object will be called
You can simply give it as:
System.out.println("Address:" +houseAddress);
Your output will look like [address1, address2, address3]
This is because the class ArrayList or its superclass would have a toString() function overridden.
Hope this helps.
assium that you have a numbers list like that
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6);
if you print the list
//method 1
// Conventional way of printing arraylist
for (int number : numbers) {
System.out.print(number);
}
//method 2
// Lambda Expression to print arraylist
numbers.forEach((Integer value) -> System.out.print(value));
//method 3
// Lambda Expression to print arraylist
numbers.forEach(value -> System.out.print(value));
//method 4
// Lambda Expression (method reference) to print arraylist
numbers.forEach(System.out::print);
Are you saying that ArrayList is storing addresses of arrays because that is what is returning from the toString call, or because that's actually what you're storing?
If you have an ArrayList of arrays (e.g.
int[] arr = {1, 2, 3};
houseAddress.add(arr);
Then to print the array values you need to call Arrays.deepToString:
for (int i = 0; i < houseAddress.size(); i++) {
System.out.println(Arrays.deepToString(houseAddress.get(i)));
}
public void printList(ArrayList<Address> list){
for(Address elem : list){
System.out.println(elem+" ");
}
}
I am not sure if I understood the notion of addresses (I am assuming houseAddress here), but if you are looking for way a to print the ArrayList, here you go:
System.out.println(houseAddress.toString().replaceAll("\\[\\]", ""));
Since Java 8, you can use forEach() method from Iterable interface.
It's a default method. As an argument, it takes an object of class, which implements functional interface Consumer. You can implement Consumer locally in three ways:
With annonymous class:
houseAddress.forEach(new Consumer<String>() {
#Override
public void accept(String s) {
System.out.println(s);
}
});
lambda expression:
houseAddress.forEach(s -> System.out.println(s));
or by using method reference:
houseAddress.forEach(System.out::print);
This way of printing works for all implementations of Iterable interface.
All of them, gives you the way of defining how the elements will be printed, whereas toString() enforces printing list in one format.
Simplest way to print an ArrayList is by using toString
List<String> a=new ArrayList<>();
a.add("111");
a.add("112");
a.add("113");
System.out.println(a.toString());
Output
[111, 112, 113]
Put houseAddress.get(i) inside the brackets and call .toString() function: i.e Please see below
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print((houseAddress.get(i)).toString());
}
This helped to me:
System.out.println(Arrays.toString(codeLangArray.toArray()));
public static void main(String[] args) {
List<Moyen> list = new ArrayList<Moyen>();
Moyen m1 = new Moyen();
m1.setCodification("c1");
m1.setCapacityManager("Avinash");
Moyen m2 = new Moyen();
m2.setCodification("c1");
m2.setCapacityManager("Avinash");
Moyen m3 = new Moyen();
m3.setCodification("c1");
m3.setCapacityManager("Avinash");
list.add(m1);
list.add(m2);
list.add(m3);
System.out.println(Arrays.toString(list.toArray()));
}
You can use an Iterator. It is the most simple and least controvercial thing to do over here. Say houseAddress has values of data type String
Iterator<String> iterator = houseAddress.iterator();
while (iterator.hasNext()) {
out.println(iterator.next());
}
Note : You can even use an enhanced for loop for this as mentioned by me in another answer
if you make the #Override public String toString() as comments,
you will have the same results as you did.
But if you implement your toString() method, it will work.
public class PrintingComplexArrayList {
public static void main(String[] args) {
List houseAddress = new ArrayList();
insertAddress(houseAddress);
printMe1(houseAddress);
printMe2(houseAddress);
}
private static void insertAddress(List address)
{
address.add(new Address(1));
address.add(new Address(2));
address.add(new Address(3));
address.add(new Address(4));
}
private static void printMe1(List address)
{
for (int i=0; i<address.size(); i++)
System.out.println(address.get(i));
}
private static void printMe2(List address)
{
System.out.println(address);
}
}
class Address{
private int addr;
public Address(int i)
{
addr = i;
}
#Override public String toString()
{
Integer iAddr = new Integer (addr);
return iAddr.toString();
}
}
You can even use an enhanced for loop or an iterator like:
for (String name : houseAddress) {
System.out.println(name);
}
You can change it to whatever data type houseAddress is and it avoids unnecessary conversions
Make sure you have a getter in House address class and then use:
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i)**.getAddress()**);
}
you can use print format if you just want to print the element on the console.
for(int i = 0; i < houseAddress.size(); i++) {
System.out.printf("%s", houseAddress.get(i));
}
Assuming that houseAddress.get(i) is an ArrayList you can add toString() after the ArrayList :
for(int i = 0; i < houseAddress.size(); i++) {
System.out.print(houseAddress.get(i).toString());
}
A general example:
ArrayList<Double> a = new ArrayList();
a.add(2.);
a.add(32.);
System.out.println(a.toString());
// output
// [2.0, 32.0]
This is a simple code of add the value in ArrayList and print the ArrayList Value
public class Samim {
public static void main(String args[]) {
// Declare list
List<String> list = new ArrayList<>();
// Add value in list
list.add("First Value ArrayPosition=0");
list.add("Second Value ArrayPosition=1");
list.add("Third Value ArrayPosition=2");
list.add("Fourth Value ArrayPosition=3");
list.add("Fifth Value ArrayPosition=4");
list.add("Sixth Value ArrayPosition=5");
list.add("Seventh Value ArrayPosition=6");
String[] objects1 = list.toArray(new String[0]);
// Print Position Value
System.err.println(objects1[2]);
// Print All Value
for (String val : objects1) {
System.out.println(val);
}
}
}
JSON
An alternative Solution could be converting your list in the JSON format and print the Json-String. The advantage is a well formatted and readable Object-String without a need of implementing the toString(). Additionaly it works for any other Object or Collection on the fly.
Example using Google's Gson:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
...
public static void printJsonString(Object o) {
GsonBuilder gsonBuilder = new GsonBuilder();
/*
* Some options for GsonBuilder like setting dateformat or pretty printing
*/
Gson gson = gsonBuilder.create();
String json= gson.toJson(o);
System.out.println(json);
}
Add toString() method to your class
houseAddress.forEach(System.out::println);
Consider using an "Enhanced for loop" I had to do this solution for a scenario in which the arrayList was coming from a class object
changing the String datatype to the appropriate datatype or class object as desired.
ArrayList<String> teamRoster = new ArrayList<String>();
// Adding player names
teamRoster.add("Mike");
teamRoster.add("Scottie");
teamRoster.add("Toni");
System.out.println("Current roster: ");
for (String playerName : teamRoster) {
System.out.println(playerName);
// if using an object datatype, you may need to use a solution such as playerName.getPlayer()
}

Complex string split in Java

Consider the following String :
5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+
Here is how I want to split string, split it with + so I get this result :
myArray[0] = "5|12345|value1|value2|value3|value4";
myArray[1] = "5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4";
if string has doesn't contain char "?" split it with "|" and continue to part II, if string does contain "?" split it and for each part split it with "|" and continue to part II.
Here is part II :
myObject.setAttribute1(newString[0]);
...
myObject.setAttribute4(newString[3]);
Here what I've got so far :
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
public void mapObject(String input){
String[] myArray = null;
if (input.contains("+")) {
myArray = input.split("+");
} else {
myArray = new String[1];
myArray[0] = input;
}
for (int i = 0; i < myArray.length; i++) {
String[] secondaryArray = null;
String[] myObjectAttribute = null;
if (myArray[i].contains("?")) {
secondaryArray = temporaryString.myArray[i].split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
} else {
myObjectAttribute = myArray[i].toString().split("\\|");
}
myObject.setAttribute1(myObjectAttribute[0]);
...
myObject.setAttribute4(myObjectAttribute[3]);
System.out.println(myObject.toString());
}
Problem :
When I split myArray, going trough for with myArray[0], everything set up nice as it should.
Then comes the myArray[1], its split into two parts then the second part overrides the value of the first(how do I know that?). I've overridden toString() method of myObject, when I finish I print the set values so I know that it overrides it, does anybody know how can I fix this?
I'm not quite sure what the intention is here, but in this snippet of code
secondaryArray = temporaryString.split("?");
for (String string : secondaryArray) {
myObjectAttribute = string.split("\\|");
}
if secondaryArray has two elements after the split operation, you are iterating over each half and re-assigning myObjectAttribute to the output of string.split("\|") each time. It doesn't matter what is in the first element of secondaryArray, as after this code runs myObjectAttribute is going to contain the result of split("\\|") on the last element in the array.
Also, there is no point in calling .toString() on a String object as you do in temporaryString = myArray[i].toString().
The code doesn't seem to be able to handle the possible expansion of strings in the secondary case. To make the code clearer, I would use a List rather than array.
private static String input = "5|12345|value1|value2|value3|value4+5|777|value1|value2|value3|value4?5|777|value1|value2|value3|value4+";
private void split(List<String> input, List<String> output, String split) {
for (String s: input) {
if (s.contains(split))
{
output.addAll(Arrays.asList(s.split(Pattern.quote(split)));
}
else
output.add(s);
}
}
public void mapObject(String input) {
List<String> inputSrings = new ArrayList<String>();
List<String> splitPlus = new ArrayList<String>();
inputStrings.add(input);
split(inputStrings, splitPlus);
List<String> splitQuest = new ArrayList<String>();
split(splitPlus, splitQuest, "?");
for (String s: splitQuest) {
// you can now set the attributes from the values in the list
// splitPipe
String[] attributes = s.split("\\|");
myObject.setAttribute1(attributes[0]);
....
myObject.setAttribute4(attributes[3]);
System.out.println(myObject);
}
}

Categories