How to get desired format from ArrayList - java

import java.net.UnknownHostException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import org.apache.log4j.Logger;
public class Test {
final static Logger logger = Logger.getLogger(Test.class);
private static DecimalFormat decimal_inpoints = new DecimalFormat("0.00");
public static void main(String args[]) throws UnknownHostException,
ParseException {
ArrayList<Integer> array_list = new ArrayList<Integer>();
array_list.add(1);
array_list.add(0);
String joinedString = array_list.toString();
System.out.println(joinedString);
}
}
How can i get output as 1,0
When i used array_list.toString(); its giving putput as [1,0] (array added )
Could you please tell me How to get 1,0 instead of [1,0]

Using Apache Commons Lang:
String join = StringUtils.join(joinList, ",");
Using Java 8
String joined = String.join(",", list);
Using Google Guava (Joiner)
Joiner joiner = Joiner.on(",");
String join = joiner.join(joinList);
Using StringBuilder
StringBuilder builder = new StringBuilder(array_list.size());
boolean isFirst = true;
for (int i : array_list){
if (isFirst) {
builder.append(i);
isFirst = false;
} else {
builder.append(", " + i);
}
}
System.out.println(builder.toString());

simpliest way is;
array_list.toString().replace("[","").replace("]","");

In Java 8 you can do it with the joining Collector:
String joinedString = list.stream()
.map(Object::toString)
.collect(Collectors.joining(", "));

When using Java 8. See here.
private toStringNoBrackets(ArrayList MyList) {
return String.join(",", MyList);
}

You can create your own class and override the toString method.
import java.util.ArrayList;
public class MyIntegerArrayList extends ArrayList<Integer>
{
#Override
public String toString(){
return super.toString().replace("[","").replace("]","");
}
}
MyIntegerArrayList myIntegerArrayList = new MyIntegerArrayList();
myIntegerArrayList.add(0);
myIntegerArrayList.add(1);
myIntegerArrayList.toString();

Use StringJoiner:
import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
public class SOPlayground {
public static void main(String[] args) {
List<Integer> array_list = new ArrayList<>();
array_list.add(1);
array_list.add(0);
StringJoiner sj = new StringJoiner(", ");
array_list.stream().forEach((i) -> {
sj.add(i.toString());
});
System.out.println(sj.toString());
}
}
Output:
1, 0

Related

OpenCSV, how to write into csv with custom processing?

I am trying to write List of POJO objects into a csv. I use opencsv and the code is very minimal:
StatefulBeanToCsv sbc = new StatefulBeanToCsvBuilder(writer)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.build();
I use Custom converters while reading, can I do something similar for write also?
For e.g.:
if field is of type List, it gets written as "[a,b]". But I
would like to do something like this: "a,b".
A field is of type LocalDataTime, I would like to write it in the format "MM/dd/yyyy"
and discard time completely in the output csv.
I want output to be something like this:
date of issue,items
"02/22/2020","a,b"
Instead of:
date of issue,items
"2020-02-22T00:00","[a,b]"
Thank you so much, appreciate any help
:)
You can use the annotations #CsvDate for set custom date format and #CsvBindAndSplitByName for the conversion of the list to string.
Please find below example:
import static java.time.temporal.ChronoUnit.MONTHS;
import com.opencsv.CSVWriter;
import com.opencsv.bean.CsvBindAndSplitByName;
import com.opencsv.bean.CsvBindByName;
import com.opencsv.bean.CsvDate;
import com.opencsv.bean.StatefulBeanToCsv;
import com.opencsv.bean.StatefulBeanToCsvBuilder;
import java.io.FileWriter;
import java.io.Writer;
import java.time.LocalDateTime;
import java.util.List;
public class Main {
public static void main(String[] args) throws Exception {
Writer writer = new FileWriter("example.csv");
StatefulBeanToCsv<Item> sbc = new StatefulBeanToCsvBuilder<Item>(writer)
.withSeparator(CSVWriter.DEFAULT_SEPARATOR)
.build();
List<Item> items = List.of(
new Item(LocalDateTime.now().minus(4, MONTHS), List.of("1", "s")),
new Item(LocalDateTime.now().minus(1, MONTHS), List.of("1", "d")),
new Item(LocalDateTime.now().minus(3, MONTHS), List.of("1", "2", "3"))
);
sbc.write(items);
writer.close();
}
public static class Item {
#CsvBindByName(column = "date")
#CsvDate(value = "yyyy-MM-dd'T'hh:mm")
private LocalDateTime date;
#CsvBindAndSplitByName(column = "list", elementType = String.class, writeDelimiter = ",")
private List<String> array;
Item(LocalDateTime date, List<String> array) {
this.date = date;
this.array = array;
}
public LocalDateTime getDate() {
return date;
}
public void setDate(LocalDateTime date) {
this.date = date;
}
public List<String> getArray() {
return array;
}
public void setArray(List<String> array) {
this.array = array;
}
}
}
The output of example.csv:
"DATE","LIST"
"2020-03-10T02:37","1,s"
"2020-06-10T02:37","1,d"
"2020-04-10T02:37","1,2,3"

is there a way to use gson well to get an list with arrays that have 4 variables in java

I'm making an 3D engine using lwjgl.
I have tried to make a class to using a list of HashMap but the HashMap only accepts 2 variables so that does not work.
Part of my code for getting the JSON file
Gson().fromJson(string.toString(), BlockIndexFile.class);
the BlockIndexFile class
public class BlockIndexFile {
List<HashMap<String, String>> blocks = new ArrayList<HashMap<String, String>>();
public void setBlocks(List<HashMap<String, String>> blocks) {
this.blocks = blocks;
}
public List<HashMap<String, String>> getBlocks(){
return this.blocks;
}
}
and the json file
{
"blocks":
[
{
"name": "Foo",
"id": "foo",
"model": "cube1",
"texture": "foo"
}
]
}
I expected to be able to use a HashMap to get the id and then use that to get the other variables like the texture and model.
HashMap can contain more than 2 variables. See below example how you could use it:
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder().create();
BlockIndexFile blockIndexFile;
try (FileReader fileReader = new FileReader(jsonFile)) {
blockIndexFile = gson.fromJson(fileReader, BlockIndexFile.class);
}
HashMap<String, String> node0 = blockIndexFile.getBlocks().get(0);
System.out.println("id => " + node0.get("id"));
System.out.println("model => " + node0.get("id"));
System.out.println("texture => " + node0.get("id"));
}
}
Above code prints:
id =>foo
model =>foo
texture =>foo
Instead Map you can create POJO and code should be much easier and concise:
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.List;
public class GsonApp {
public static void main(String[] args) throws Exception {
File jsonFile = new File("./resource/test.json").getAbsoluteFile();
Gson gson = new GsonBuilder().create();
BlockIndexFile blockIndexFile;
try (FileReader fileReader = new FileReader(jsonFile)) {
blockIndexFile = gson.fromJson(fileReader, BlockIndexFile.class);
}
Block node0 = blockIndexFile.getBlocks().get(0);
System.out.println(node0);
}
}
class BlockIndexFile {
private List<Block> blocks = new ArrayList<>();
// getters, setters
}
class Block {
private String id;
private String name;
private String model;
private String texture;
// getters, setters, toString
}
Above code prints:
Block{id='foo', name='Foo', model='cube1', texture='foo'}

GSON: Serialize object with java.util.TreeSet

How can I serialize a TreeSet properly? In order to give you an idea of what's not working I've set up this little demo project. The main goal is to print a JSON string of my QData object.
App.java
package de.company.gsonserializer;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
public class App
{
public static void main( String[] args )
{
QData qdata = new QData();
ArrayList<LData> arrayList = new ArrayList<LData>(1);
LData l = new LData();
Map<String, String> unsortedBuabList = new HashMap<String, String>();
for (int i = 0; i < 5; i++) {
unsortedBuabList.put("Key-" + i, "Value" + i);
}
SortedSet<Map.Entry<String, String>> sortedBuabList = new TreeSet<Map.Entry<String, String>>(
new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> e1, Map.Entry<String, String> e2) {
return e1.getValue().compareTo(e2.getValue());
}
});
sortedBuabList.addAll(unsortedBuabList.entrySet());
l.setBuabList(sortedBuabList);
arrayList.add(l);
qdata.setLocations(arrayList);
System.out.println( qdata.toString() );
}
}
QData.java
package de.it2media.gsonserializer;
import java.util.ArrayList;
import com.google.gson.Gson;
public class QData {
private ArrayList<LData> locations = new ArrayList<LData>(0);
public ArrayList<LData> getLocations() {
return locations;
}
public void setLocations(ArrayList<LData> locations) {
this.locations = locations;
}
#Override
public String toString(){
Gson gson = new Gson();
String thisObj = gson.toJson(this);
return thisObj;
}
}
LData.java
package de.it2media.gsonserializer;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.Map.Entry;
public class LData {
private SortedSet<Entry<String, String>> buabList = new TreeSet<Map.Entry<String, String>>();
public SortedSet<Entry<String, String>> getBuabList() {
return buabList;
}
public void setBuabList(SortedSet<Entry<String, String>> buabList) {
this.buabList = buabList;
}
}
The output: {"locations":[{"buabList":[{},{},{},{},{}]}]}
Expected output would be something like: {"locations":[{"buabList":[{"key":"Key-0","value":"Value0"},{"key":"Key-1","value":"Value1"},{"key":"Key-2","value":"Value2"},{"key":"Key-3","value":"Value3"},{"key":"Key-4","value":"Value4"}]}]}
Do you might know why GSON is not working as I'd expect it to work?
Thanks for any help, highly appreciated!
The problem you are running into has nothing to do with the TreeSet, but rather with the fact that GSON does not know how to serialize a map Entry in the way that you would like. You therefore need to write a custom serializer for it, which looks something like this:
public static class EntrySerializer implements JsonSerializer<Entry<String, String>> {
#Override
public JsonElement serialize(Entry<String, String> entry, Type typeOfSrc, JsonSerializationContext context) {
JsonElement serializedKey = context.serialize(entry.getKey());
JsonElement serializedValue = context.serialize(entry.getValue());
JsonObject jsonObject = new JsonObject();
jsonObject.add("key", serializedKey);
jsonObject.add("value", serializedValue);
return jsonObject;
}
}
When you create the Gson object, you then need to register this custom serializer:
Gson gson = new GsonBuilder()
.registerTypeAdapter(Entry.class, new EntrySerializer())
.create();
You can read more about custom serializers and deserializers in the GSON documentation.

Convert List<Object> to List<String> without for?

How can I convert a List of Objects to corresponding List of Strings without scanning all elements by for loop?
You could try this:
List<String> variable = (List<String>)(List<?>) yourList;
In the comments you specified that you wanted to call the toString() method. This is possible with guava (https://code.google.com/p/guava-libraries/):
import com.google.common.base.Function;
import com.google.common.collect.Lists;
import java.util.ArrayList;
import java.util.List;
public class Application {
public static void main(String[] args) {
Function<Object, String> objectToString = new Function<Object, String>() {
public String apply(Object object) {
return object.toString();
}
};
List<Object> yourList = new ArrayList<Object>();
yourList.add("foo");
List<String> strings = Lists.transform(yourList, objectToString);
}
}

Lists<List<Double>>adding to HashMap

So, after request of compiling code, here it is. And the problem is that after adding second Hash element Called "B", the output messes up.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test {
public static void main(String[] args) {
Map<String, List<List<Double>>> alphabet = new HashMap<String,List<List<Double>>>();
List<List<Double>> something = new ArrayList<List<Double>>();
List<Double> stuffList = new ArrayList<Double>();
stuffList.add(3.1);
stuffList.add(3.2);
stuffList.add(3.3);
something.add(stuffList);
alphabet.put("A", something);
System.out.println(something);
System.out.println(alphabet);
stuffList.clear();
something.clear();
stuffList.add(3.4);
something.add(stuffList);
alphabet.put("B", something);
System.out.println(something);
System.out.println(alphabet);
}
}
The output is:
[[3.1, 3.2, 3.3]]
{A=[[3.1, 3.2, 3.3]]}
[[3.4]]
{A=[[3.4]], B=[[3.4]]}
Which in my opinion and needs, should be:
[[3.1, 3.2, 3.3]]
{A=[[3.1, 3.2, 3.3]]}
[[3.4]]
{A=[[3.1, 3.2, 3.3]], B=[[3.4]]}
You are still referencing old instances of the lists. This should work as expected:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class test {
public static void main(String[] args) {
Map<String, List<List<Double>>> alphabet = new HashMap<String,List<List<Double>>>();
List<List<Double>> something = new ArrayList<List<Double>>();
List<Double> stuffList = new ArrayList<Double>();
stuffList.add(3.1);
stuffList.add(3.2);
stuffList.add(3.3);
something.add(stuffList);
alphabet.put("A", something);
System.out.println(something);
System.out.println(alphabet);
// Create new instances:
something = new ArrayList<List<Double>>();
stuffList = new ArrayList<Double>();
stuffList.add(3.4);
something.add(stuffList);
alphabet.put("B", something);
System.out.println(something);
System.out.println(alphabet);
}
}
In Java objects are always taken by reference.
Which means that
stuffList.clear();
something.clear();
stuffList.add(3.4);
operates on the same lists you put in the map by the key "A".
So in the end the map contains the same list twice.

Categories

Resources