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.
Related
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
I have a List and A is defined below.
How do i add in a Map with Key as Long and values as List of Strings.
Class A
{
Long in;
List<String> out;
}
Map<Long,List<String>>
Create a Hashmap object, with key Long and value List. Add items with put(key,value) and retrieve them with get
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] args) {
Map<Long,List<String>> myMap=new HashMap<Long,List<String>>();
List<String> myList=new ArrayList<String>();
myList.add("abc");
myList.add("xyz");
myMap.put(new Long(1), myList);
for(int i=0;i<myList.size();i++)
System.out.println(myMap.get(new Long(1)).get(i));
}
}
1.) Create HashMap with Key as Long and value as List<String>.
2.) Use put method of HashMap, as below.
public static void main(String[] args) {
Map<Long, List<String>> myMap = new HashMap<Long, List<String>>();
myMap.put(101L, new ArrayList<String>());
}
I'm having trouble applying sorting mechanism through my application.
Reason was sometimes sort are not accurate and also the comparator thing in java still not clear for me, but i have used sort here and there.
Now, current problem is as follows.
I have
HashMap<String, ModelX.ContactModel> unsortedModelContacts =
new HashMap<String,ModelX.ContactModel>(contacts.size());
After that I fached
contactlist and using for loop I have put the values as follows:
unsortedModelContacts.put(stringvalue, modelContact);
//object having name , and other details
How can I sort the unsortedModelContacts sorting modelContact.getName property?
If your map's key is different from the name field then you can consider using this approach. Writing a separate comparator
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import sample.ModelX.ContactModel;
public class SortMapSample {
public static void main(String[] args) throws Exception {
Map<String, ModelX.ContactModel> unsortedModelContacts = new HashMap<String,ModelX.ContactModel>(10);
unsortedModelContacts.put("1", new ModelX.ContactModel("James"));
unsortedModelContacts.put("2", new ModelX.ContactModel("Mary"));
unsortedModelContacts.put("3", new ModelX.ContactModel("John"));
unsortedModelContacts.put("4", new ModelX.ContactModel("Amanda"));
unsortedModelContacts.put("5", new ModelX.ContactModel("Charles"));
System.out.println(sortMap(unsortedModelContacts));
}
private static Map<String, ModelX.ContactModel> sortMap(
Map<String, ModelX.ContactModel> unsortedMap) {
List<Entry<String, ModelX.ContactModel>> list = new LinkedList<Entry<String, ModelX.ContactModel>>(
unsortedMap.entrySet());
Collections.sort(list,
new Comparator<Entry<String, ModelX.ContactModel>>() {
#Override
public int compare(Entry<String, ContactModel> o1,
Entry<String, ContactModel> o2) {
return o1.getValue().getName().compareTo(o2.getValue().getName());
}
});
Map<String, ModelX.ContactModel> sortedMap = new LinkedHashMap<String, ModelX.ContactModel>();
for(Entry<String, ModelX.ContactModel> item : list){
sortedMap.put(item.getKey(), item.getValue());
}
return sortedMap;
}
}
SortedMap<String,ModelX.ContactModel> sortedModelContacts = new TreeMap<>();
for( ModelX.ContactModel modelContact: contactlist ){ // same list as before
sortedModelContacts.put( modelContact.getName(), modelContact);
}
You can now access entries of this map in sort order of the name property.
Note: this assumes that names are unique. If this isn't true, you'll have to use a multimap or
Map<String,ModelX.Set<ContactModel>>
and modify the put and other accesses accordingly.
I want to create list by doing this
List<String> myList = new ArrayList<String>();
but it's not recognized, i don't know why:
Eclipse suggest me to modify the syntax :
First eclipse consider that the type List is not generic and it removes the first String brackets
List myList = new ArrayList<String>();
and then change the type of my List and finally i have :
ArrayList<String> myList = new ArrayList<String>();
I really don't understand why it doesn't work.
How to make a new List in Java
I read this post and try again with an other type it's the same problem.
EDIT:my code look like this
import java.util.ArrayList;
import java.awt.List;
public class Test {
public static void main(String[] args){
List<String> myList = new ArrayList<String>();
}
}
The problem was solved by changing
import java.awt.List;
to
import java.util.List;
Does your code look like this?
import java.util.ArrayList;
import java.util.List;
public class Example {
public static void main(String[] args) throws Exception {
List<String> myList = new ArrayList<String>();
}
}
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);
}
}