Issue with string array - java

The below code gives result as test:[someproduct, someproduct, someproduct, someproduct, someproduct]. I am expecting result as ["someproduct", "someproduct", "someproduct", "someproduct", "someproduct"] so that I will push the string array into json response
String[] Id = new String[5];
for (int i = 0; i < 5; i++) {
Id[i] ="someproduct";
}
System.out.println("test:"+Arrays.toString(Id));
writer.key("product").value(Arrays.toString(Id));
When I try access the jsonresponse like response.product[0], i am getting first character '[' alone. I suppose to get first item(someproduct) of the array.
Please help me to resolve.

the problem is the method you are using is not sufficient.
one way of doing this, is to use another type of array (e.g. ArrayList) then Override its toString method.
here is an example:
public static void main(String... args) throws Exception{
ArrayList<String> array=new ArrayList<String>(){
/**
*
*/
private static final long serialVersionUID = 1L;
#Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean isFirst=true;
for(String s : this){
if(!isFirst){
sb.append(",");
}
isFirst=false;
sb.append("\""+s+"\"");
}
sb.append("]");
return sb.toString();
}
};
for (int i = 0; i < 5; i++) {
array.add("someproduct");
}
System.out.println(array);
}
output:
["someproduct","someproduct","someproduct","someproduct","someproduct"]
NOTE:
There are many ways to make this code reusable, e.g.
creating a new class ArrayListWithNicePrint that extends ArrayList
creating a static method that returns you a fresh ArrayList with nice Print (I prefer this one really)
EDIT: (Based ON comment):
public class ArrayListWithNicePrint<E> extends ArrayList{
#Override
public String toString(){
StringBuilder sb = new StringBuilder();
sb.append("[");
boolean isFirst=true;
for(Object s : this){
if(!isFirst){
sb.append(",");
}
isFirst=false;
sb.append("\""+s.toString()+"\"");
}
sb.append("]");
return sb.toString();
}
}
Testing:
public class Testing{
public static void main(String... args){
ArrayListWithNicePrint<String> list= new ArrayListWithNicePrint<String>();
list.add("hi");
list.add("hello");
System.out.println(list);
}
}

Try this :
String[] Id = new String[5];
for(int i = 0; i < 5; i++)
{
Id[i] =" **\"someproduct\"** ";
}
hope it will work

You can use some JSON converter library, or as a quickfix you could use something like this:
String[] Id = new String[5];
for (int i = 0; i < 5; i++) {
Id[i] ="\"someproduct\"";
}
String arrOutput = Arrays.toString(Id).replaceAll("\\[", "{").replaceAll("\\]", "}");
System.out.println("test:"+ arrOutput);
writer.key("product").value(arrOutput);
Depending on the content on your array elements more workaround would be needed. Maybe if you write more information we can help you better.

why dont u try putting it into a List and then use Gson to convert the whole list into json format, dig a bit to get the correct format of json u want. for retrieving u can retrieve easily with the tag names associated with each element. What u require is not very clear so this is the best guess i can make

Try with this code. it will resolve your issue.
String[] Id = new String[5];
for (int i = 0; i < 5; i++) {
Id[i] ="\"someproduct\"";
}
System.out.println("test:"+Arrays.toString(Id).replace('[', '{').replace(']', '}'));

When usin the JSONWriter object, you should use the built in array() and endArray() methods like this:
writer.key("product").array();
for (int i=0; i<5; i++) {
writer.object();
writer.key("name").value("someproductname" + i);
writer.endObject();
}
writer.endArray();
http://www.json.org/javadoc/org/json/JSONWriter.html

Related

Alphabetically sort contents of file using methods (Java)

The title might be a little misleading but I am writing a piece of code that has this as the contents of the text file:
04/26/16 Sega 3D Classics Collection
07/14/16 Batman: Arkham Underworld
06/24/16 Tokyo Mirage Sessions #FE
Essentially I want them to be in alphabetical order and it should make a brand new file that looks like this:
Batman: Arkham Underworld
Sega 3D Classics Collection
Tokyo Mirage Sessions #FE
What I have tried is to use the indexOf() method to extract only the names of the list of games from my existing text file. I have also tried to store them in a new array to avoid confusion for the computer. The problem is that when I try to store the indexOf of the info array into a new array, the line gives an error of "cannot convert from int to string" and I am not sure on how to fix the error.
This is my code below:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Scanner;
public class Main{
public static void main (String[]args) throws IOException{
File file = new File("releasedates.txt");
String []arr = input(file);
output(file,arr);
outputSort1(file, arr);
}
public static String[]input (File file) throws FileNotFoundException{
String[]arr = new String[3];
Scanner sc = new Scanner(file);
for(int i = 0; i < arr.length; i++){
arr[i] = sc.nextLine();
}
return arr;
}
public static void output(File file, String[] info) throws IOException{
FileWriter writer = new FileWriter("fileName.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByMonth(String[]info){
String temp;
for (int j = 0; j < info.length; j++) {
for (int i = j + 1; i < info.length; i++) {
if (info[i].compareTo(info[j]) < 0) {
temp = info[j];
info[j] = info[i];
info[i] = temp;
}
}
}
}
public static void outputSort1(File file,String[] info) throws IOException{
sortByMonth(info);
FileWriter writer = new FileWriter("fileNameSorted1.txt");
for(String aString:info){
writer.write(aString);
}
writer.close();
}
public static void sortByName(String[]info){
String[] names = new String[3];
for(int i = 0; i < info.length; i ++){
names[i] = info[i].indexOf(" " ,info.length);
}
String temp;
for (int j = 0; j < names.length; j++) {
for (int i = j + 1; i < names.length; i++) {
if (names[i].compareTo(names[j]) < 0) {
temp = names[j];
names[j] = names[i];
names[i] = temp;
}
}
}
}
}
You've declared names array as String[] so you can't assign integer to it. indexOf method returns integer.
public static void sortByName(String[]info) {
String[] names = new String[3]; //<-- declaration suggests store string
for (int i = 0; i < info.length; i++) {
names[i] = info[i].indexOf(" ", info.length);//<-you are assigning integer
}
I think what you are trying to do is like this:
names[i] = info[i].substring(info[i].indexOf(" "), info[i].length());
Use java.nio APIs for file implementations as java.io apis are outdated. Also, if you use Stream operations then the implementation becomes much easier:
public class Test {
public static void main(String[] args) throws Exception {
Path file = Path.of("e:\\releasedates.txt");
List<String> records = Files.readAllLines(file);
List<String> sortedByName = records.stream()
.map(s -> s.substring(s.indexOf(" "), s.length()))
.sorted(String::compareTo)
.collect(Collectors.toList());
System.out.println(sortedByName);
Files.write(Path.of("e:\\fileNameSorted.txt"), sortedByName);
List<String> sortedByDate = records.stream().sorted(Test::compareDates)
.map(s -> s.substring(s.indexOf(" "), s.length()))
.collect(Collectors.toList());
System.out.println(sortedByDate);
Files.write(Path.of("e:\\fileDateSorted.txt"), sortedByDate);
}
public static int compareDates(String d1, String d2) {
d1 = d1.substring(0, d1.indexOf(" "));
d2 = d2.substring(0, d2.indexOf(" "));
LocalDate ld1 = LocalDate.parse(d1,
DateTimeFormatter.ofPattern("MM/dd/yy"));
LocalDate ld2 = LocalDate.parse(d2,
DateTimeFormatter.ofPattern("MM/dd/yy"));
return ld1.compareTo(ld2);
}
}
Answer by #onkar ruikar is correct. indexOf returns int and you are trying to store it in String. I would like to extend his answer, where you can store the game/movie names in TreeSet instead of Array, so that by default it will be sorted in alphabetical order.
If you want to allow duplicate game/movie names, then you can use ArrayList and call Collections.sort(<array list>) method, which will sort the ArrayList in alphabetical order.
Here is the detailed answer of how can we sort Collections in Java: https://stackoverflow.com/a/8725470/3709922

Converting List<Object> to String returns empty results

Disclaimer : I'm using this Post, as reference for List<Object> to List<String> and this Post for Java List<String> of strings to a JavaScript array.
I've List<Seat> and I want to get all values of it in a comma separated String, I tried in this way
import java.util.*;
import java.lang.*;
class Rextester
{
public Rextester(){
Seat seat1 = new Seat();
seat1.setSeatNumber(1);
Seat seat2 = new Seat();
seat2.setSeatNumber(2);
Seat seat3 = new Seat();
seat3.setSeatNumber(3);
List<Seat> seatList = new ArrayList<Seat>();
seatList.add(seat1);
seatList.add(seat2);
seatList.add(seat3);
Utility util = new Utility();
String stringSeats = util.toJavascriptArray(seatList);
System.out.println("JavaScriptArray is " + stringSeats);
}
public static void main(String args[])
{
new Rextester();
}
private class Seat {
private Integer seatNumber;
public Integer getSeatNumber() {
return this.seatNumber;
}
public void setSeatNumber(Integer seatNumber) {
this.seatNumber = seatNumber;
}
public String toString() {
return ""+ seatNumber;
}
}
private class Utility {
public String toJavascriptArray(List<Seat> listSeats){
List<String> strings = new ArrayList<String>();
for (Seat object : listSeats) {
strings.add(object != null ? object.toString() : null);
}
String[] arr = new String[strings.size()];
arr = strings.toArray(arr);
StringBuffer sb = new StringBuffer();
sb.append("[");
for(int i=0; i<arr.length; i++){
if(i+1 < arr.length){
sb.append(",");
}
}
sb.append("]");
return sb.toString();
}
}
}
but this gives me
JavaScriptArray is [,,]
on console, am I making some mistakes? an online working code is http://rextester.com/NDUGT61105
You didn't append iterated element, see below
for (int i = 0; i < arr.length; i++) {
sb.append(arr[i]); // add this
if (i + 1 < arr.length) {
sb.append(",");
}
}
have a look at the toString implementations of Arrays and List
Simply you can return
strings.toString()
or
Arrays.toString(arr)
To get the expected result
Another option, if you're using Java 8 is using StringJoiner:
https://docs.oracle.com/javase/8/docs/api/java/util/StringJoiner.html
You forgot to append the array elements to the string buffer!
Add
sb.append(arr[i]);
inside the loop where you prepare the string buffer and everything is ok

How do I override the toString method to display elements in a list in Java?

I have been trying to figure this out for hours, but I am unable find an answer that works.
For completeness, I have posted the entire code below. If I do not Override the toString method, I get the representation for the hashcode for the object.
I tried using the following:
public String toString(List<?> list) {
String result = " ";
for (int i = 0; i < list.size(); i++) {
result += " " + list.get(i);
}
return result;
}
However, this does not seem to help as I still get a reference to the hashcode. I understand that this is because I am not overriding the toString method properly; I get an error when I include the #Override annotation, but this is as far as I have been able to get.
I looked at some other answers that said that overriding the toString method would not be useful in the case of Lists/Collections, but no proper guidance for another alternative was given.
public class WordsContainer {
Collection<String> wordList = new ArrayList<String>();
public void wordGroup1() {
wordList.add("Ant");
wordList.add("Almond");
/// more words
}
public Collection<String> getRandomWords() {
wordGroup1();
LinkedList<String> wordLinkedList = new LinkedList<String>(wordList);
ArrayList<String> subList = new ArrayList<String>();
int i = 0;
while (i < 6) {
int index = (int) Math.random() * 10;
if (!subList.contains(wordLinkedList.get(index))) {
subList.add(wordLinkedList.get(index));
i++;
}
}
return subList;
}
public String toString(List<?> list) {
String result = " ";
for (int i = 0; i < list.size(); i++) {
result += " " + list.get(i);
}
return result;
}
}
public class wordsContainerTest {
public static void main(String[] args) {
wordsContainer list1 = new wordsContainer();
list1.wordGroup1();
System.out.println(list1);
}
}
EDIT :
Apologies, I forgot to mention that I tried removing the parameters in the Override method like this:
public String toString() {
LinkedList<String> list = new LinkedList<>()
String result = " ";
for (int i = 0; i < list.size(); i++) {
result += " " + list.get(i);
}
return result;
}
But when I ran the code, the console displayed nothing. I realize this is because I instantiated an empty list, but I at this point, I didnt know what else to do.
toString() has no arguments. Overwrite it like so (assuming you are extending a List class):
#Override
public String toString() {
String result = " ";
for (int i = 0; i < this.size(); i++) {
result += " " + this.get(i);
}
return result;
}
UPDATE 01
Ok, it seems that what you really want to do is print the contents of the list that is encapsulated by your WordsContainer.
Override toString of WordsContainer like so:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(" "); // remove this if you do not want two spaces at the front of the returned string
for (int i = 0; i < this.wordList.size(); i++) {
sb.append(" " + this.wordList.get(i).toString());
}
return sb.toString();
}
Note that you have to change the declaration of wordList to be of type List<String>.
UPDATE 02
This answers the followup question in comments.
You can declare a static utility method that builds a string representation of the contents of any given list of strings like so:
public static String getStringRepresentation(List<String> list) {
StringBuilder sb = new StringBuilder();
sb.append(" "); // remove this if you do not want two spaces at the front of the returned string
for (int i = 0; i < list.size(); i++) {
sb.append(" " + list.get(i).toString());
}
return sb.toString();
}
And use this method like so:
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("foo");
list.add("bar");
String listStringRepr = WordsContainer.getStringRepresentation(list);
System.out.println(listStringRepr);
}
You do not match the signature of Object.toString(). (I usually let my IDE generate a stub, helps plenty ;))
Just add this to your existing code:
#Override
public String toString() {
return "WordsContainer{" +
"wordList=(" + toString(wordList) + ")}";
}
Though, you will have to declare wordList as List.
UPDATE:
To clarify the last remark in the original answer:
In your own wrapper WordsContainer you declare wordList as
Collection<String> wordList = new ArrayList<String>();
while in your own attempt at implementing toString you use List<?> as parameter type. Therefore, the above code would not work without one other refactoring. Either declare wordList as List<String>
List<String> wordList = new ArrayList<String>();
or refactor your toString() to take a Collection<?> as argument:
public String toString(Collection<?> list) {
String result = " ";
for (Object item : list) {
result += " " + item.toString();
}
return result;
}
Since you have provide parameter to your toString() method, it is no more the Object's class toString() method. It is a new method and works as a overloaded version of Object's toString() not the overridden version. Remove the parameter. To work the toString() properly you need to have the exactly same method signature -
public String toString(){
//implmentation
}
Just call toString() with the List element itself.
Like so:
import java.util.List;
import java.util.LinkedList;
public class WordList {
List<String> list = new LinkedList<String>();
public static void main(String []args) {
System.out.println(new WordList());
}
#Override
public String toString() {
String result = "";
list.add("Hello");
list.add("World");
for (int i = 0; i < list.size(); i++) {
result += " " + list.get(i).toString();//call toString on element of the list
}
return result;
}
}
Output: ' Hello World'
package listtostringmethod;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class ListToStringMethod {
enter code here
public static void main(String[] args) {
// TODO code application logic here
//List<String> s = Arrays.asList("a","b","c");
//s.toString();
MyList myList = new MyList();
myList.add("a");
myList.add("b");
//myList.toString();
System.out.println(myList.toString());
}
}
class MyList extends ArrayList {
#Override
public String toString (){
StringBuffer retVal = new StringBuffer();
Iterator iterator = this.iterator();
while (iterator.hasNext()){
retVal.append(iterator.next()+",");
}
return retVal.toString();
}
}
The code is straight forward. Hope this helps you.

return multiple values java for removing last part of a word

In my code, fromright method checks the length of last[] and returns only one string. I want to return all matched values. What's the solution?
public static String last[]={"es","e","s"};
public static void main(String[] args) {
text tx=new text();
String checkString = "lives";
String fin=tx.fromright(checkString);
System.out.println("remaining: "+fin);
}
public String fromright(String wrd) {
String tmp="";
for (int i = 0; i < last.length; i++) {
tmp=wrd.substring(0, wrd.length()-last.length);
}
return tmp;
}
You are overriding your tmp variable in your for loop every time. So you can only get one result.
Use this instead or smth. similiar which can hold multiple values.
public List<String> fromright(String wrd) {
List<String> tmp= new ArrayList<String>();
for (int i = 0; i < last.length; i++) {
tmp.add(wrd.substring(0, wrd.length()-last.length));
}
return tmp;
EDIT:
This does not work anymore.
String fin=tx.fromright(checkString);
^
Replace it with
List<String> fin= new ArrayList<String>(tx.fromright(checkString));
And print out all values with this
for(String s : fin) System.out.println(s);
public List<String> fromright(String wrd) {
List<String> result = new ArrayList<>();
for (int i = 0; i < last.length; i++) {
if(wrd.endsWith(last[i]))
result.add(last[i]);
}
return result;

java delete reverse string in list

I have struct Array or List String like:
{ "A.B", "B.A", "A.C", "C.A" }
and I want delete reverse string from list that end of only:
{ "A.B", "A.C" }
how type String use and how delete reverse String?
To reverse a string I recommend using a StringBuffer.
String sample = "ABC";
String reversed_sample = new StringBuffer(sample).reverse().toString();
To delete object form you ArrayList use the remove method.
String sample = "ABC";String to_remove = "ADS";
ArrayList<String> list = new ArrayList<Sample>();
list.add(to_remove);list.add(sample );
list.remove(to_remove);
You can get use of a HashMap to determine whether a string is a reversed version of the other strings in the list. And you will also need a utility function for reversing a given string. Take a look at this snippets:
String[] input = { "A.B", "B.A", "A.C", "C.A" };
HashMap<String, String> map = new HashMap<String, String>();
String[] output = new String[input.length];
int index = 0;
for (int i = 0; i < input.length; i++) {
if (!map.containsKey(input[i])) {
map.put(reverse(input[i]), "default");
output[index++] = input[i];
}
}
A sample String-reversing method could be like this:
public static String reverse(String str) {
String output = "";
int size = str.length();
for (int i = size - 1; i >= 0; i--)
output += str.charAt(i) + "";
return output;
}
Output:
The output array will contain these elements => [A.B, A.C, null, null]
A code is worth thousand words.....
public class Tes {
public static void main(String[] args) {
ArrayList<String> arr = new ArrayList<String>();
arr.add("A.B");
arr.add("B.A");
arr.add("A.C");
arr.add("C.A");
System.out.println(arr);
for (int i = 0; i < arr.size(); i++) {
StringBuilder str = new StringBuilder(arr.get(i));
String revStr = str.reverse().toString();
if (arr.contains(revStr)) {
arr.remove(i);
}
}
System.out.println(arr);
}
}
You can do this very simply in O(n^2) time. Psuedocode:
For every element1 in the list:
For every element2 in the list after element1:
if reverse(element2).equals(element1)
list.remove(element2)
In order to make your life easier and prevent ConcurrentModificationException use Iterator. I won't give you the code because it's a good example to learn how to properly use iterators in Java.
Reverse method:
public String reverse(String toReverse) {
return new StringBuilder(toReverse).reverse().toString();
}
Edit: another reverse method:
public String reverse(String toReverse) {
if (toReverse != null && !toReverse.isEmpty) {
String[] elems = toReverse.split(".");
}
StringBuilder reversedString = new StringBuilder("");
for (int i = elems.length - 1; i >= 0; i++) {
reversedString.append(elems[i]);
reversedString.append(".");
}
return reversedString.toString();
}
Check this
public static void main(String arg[]){
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
List<String> strList = new ArrayList<String>();
strList.add("A.B");
strList.add("B.A");
strList.add("A.C");
strList.add("C.A");
Iterator<String> itr = strList.iterator();
while(itr.hasNext()){
String [] split = itr.next().toUpperCase().split("\\.");
if(str.indexOf(split[0])>str.indexOf(split[1])){
itr.remove();
}
}
System.out.println(strList);
}
output is
[A.B, A.C]
You can iterate the list while maintaining a Set<String> of elements in it.
While you do it - create a new list (which will be the output) and:
if (!set.contains(current.reverse())) {
outputList.append(current)
set.add(current)
}
This solution is O(n*|S|) on average, where n is the number of elements and |S| is the average string length.
Java Code:
private static String reverse(String s) {
StringBuilder sb = new StringBuilder();
for (int i = s.length()-1 ; i >=0 ; i--) {
sb.append(s.charAt(i));
}
return sb.toString();
}
private static List<String> removeReverses(List<String> arr) {
Set<String> set = new HashSet<String>();
List<String> res = new ArrayList<String>();
for (String s : arr) {
if (!set.contains(reverse(s))) {
res.add(s);
set.add(s);
}
}
return res;
}
public static void main(String[]args){
String[] arr = { "a.c" , "b.c", "c.a", "c.b" };
System.out.println(removeReverses(arr));
}
will yield:
[a.c, b.c]

Categories