Redis with java - java

public void verProduto(){
//System.out.println("Digite o codigo do produto : - ");
//produt.setCodigo(scan.nextInt());
List<String> list = (List<String>) jeproduto.keys("*");
for(int i = 0; i<list.size(); i++) {
System.out.println("List of stored keys:: "+list.get(i));
}
}
This code returns error:
java.util.HashSet cannot be cast to java.util.List
Could someone help?

You havent given a lot of detail but you can try:
List<String> list = new ArrayList<String>(jeproduto.keys("*"));

Assuming you are using jedis and that the jeproduto object is a Jedis instance, per the javadocs, the keys method returns the type Set<String>
You have two options:
Change your collection type to a Set instead of a List:
Set<String> keySet = jeproduto.keys("*");
for (String key : keySet) {
System.out.println("List of stored keys: " + key);
}
Or
If you truly need a List, do what CannedMoose mentioned and take advantage of the ArrayList constructor that allows you to pass another collection.
List<String> list = new ArrayList<>(jeproduto.keys("*"));

Since your code is not fully completed.
My Assumption is
jeproduto = new HashSet<String>
then
List<String> list = (List<String>) jeproduto.keys("*"); line should be
// Creating a List of HashSet elements
List<String> list = new ArrayList<String>(hset);
if you want to convert Hashset to List, please find the sample code below.
public static void main(String[] args) {
// Create a HashSet
HashSet<String> hset = new HashSet<String>();
//add elements to HashSet
hset.add("A");
hset.add("B");
hset.add("C");
hset.add("D");
hset.add("E");
// Displaying HashSet elements
System.out.println("HashSet contains: "+ hset);
// Creating a List of HashSet elements
List<String> list = new ArrayList<String>(hset);
// Displaying ArrayList elements
System.out.println("ArrayList contains: "+ list);
}

Related

How to edit the Hashmap list values based on the Key

I need to edit the list values based on the key .
My code is:
HashMap<String,List<String>> map= new HashMap<String,List<String>>()
List<String> listOMSColorCode = new ArrayList<String>()
List<String> listOMSColorCodeDisplayOrder = new ArrayList<String>()
listOMSColorCode.add("orange")
listOMSColorCode.add("apple")
listOMSColorCode.add("banana")
map.put("Key1",listOMSColorCode)
after some logic happen here , Now I want to replace/edit apple with grapes in the same index of map list.
You could use a ListIterator for that:
for(ListIterator<String> li = listOMSColorCode.listIterator(); li.hasNext(); ) {
if(li.next().equals("apple")) {
li.set("grape");
}
}
if(li.next().equals("apple")) { checks if the current element of the listIterator is an "apple" and if it is. It replaces that element with "grape" via the the ListIterator.set() method
Not very efficient, because it iterates the list for every occurence, but this will replace all occurences:
List<String> modifiedList = map.get("Key1");
int index = 0;
while((index = modifiedList.indexOf("apple")) != -1){
modifiedList.set(index, "grapes");
}
Or using a utility method from Collections class:
List<String> modifiedList = map.get("Key1");
Collections.replaceAll(modifiedList, "apple", "grapes");

How to store all ArrayList<ArrayList<String>> values into ArrayList<String>?

I am having issue to store all values of ArrayList<ArrayList<String>> into ArrayList<String>. Here stylistIDArray and durationArray are array of array. I want to store all their values in stylistId and duration respectively. The stylistid and duration are array of string.
Here's my attempt, but it stores only the last item of each array of array.
ArrayList<ArrayList<String>> stylistIDArray;
ArrayList<ArrayList<String>> durationArray;
stylistIDArray = differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray = differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String>stylistId = new ArrayList<>();
ArrayList<String>duration = new ArrayList<>();
for(int i=0; i<stylistIDArray.size(); i++) {
stylistId = stylistIDArray.get(i);
duration = durationArray.get(i);
}
Note : I have already tried this, but doesn't work for me.
To be generic, First let be an list of list of objects
List<List<Object>> listOfList;
That you want to put into a list of object
List<Object> result;
Note the result list will contain every object contain is the input list. This transformation will loose the information of which object was in which list.
You have to loop through the listOfList. At each loop you obtain a list of object (List<Object> listOfObject). Then loop through these lists to obtain every object (Object o). Then add these object to the result list (result.add(o)).
for(List<Object> listOfObject : listOfList) {
for(Object o : listOfObject) {
result.add(o);
}
}
In your case, the problem is that you use affectation instead of add(). At every loop this replaces the value by the new one. So at the end you have stored only the last item of each list.
stylistId=stylistIDArray.get(i); //This replace the existing stylistId
Instead try something like
ArrayList<ArrayList<String>> stylistIDArray;
ArrayList<ArrayList<String>> durationArray;
stylistIDArray = differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray = differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String> stylistId = new ArrayList<>();
ArrayList<String> duration = new ArrayList<>();
for(ArrayList<String> l : stylistIDArray) {
for(String s : l) {
stylistId.add(s);
}
}
for(ArrayList<String> l : durationArray ) {
for(String s : l) {
duration.add(s);
}
}
You doing wrong operation with arraylist, in loop you are getting data from stylistIDArray and assign to aryalist, not inserting in list, have look this
stylistIDArray=differentGenderServicesAdapter.getSelectedStylistIdArray();
durationArray=differentGenderServicesAdapter.getSelectedDurArray();
ArrayList<String>stylistId=new ArrayList<>();
ArrayList<String>duration=new ArrayList<>();
for(int i=0; i<stylistIDArray.size(); i++) {
stylistId.add(stylistIDArray.get(i));
duration.add(durationArray.get(i));
}
Hope it will help you!

how to get value from 2d arraylist

i have arraylists named sub and main,
ArrayList main = new ArrayList();
ArrayList sub=new ArrayList();
i add value to sub and then add sub to main.
example;
sub.add(1);
sub.add(2);
main.add(sub);
now i want to get all values inside sub
so i used following one but .get(j) gives me the error get >> canot find symbol
for (int i=0;i<main.size();i++) {
System.out.println();
for (int j=0;j<sub().size();j++) {
System.out.print(main.get(i).get(j));//error line
}
}
how can i get all values inside subarray of main arraylist
When you declare a variable as
ArrayList main;
This list holds Objects. This means that main.get(i) will only return an Object, even if you add ArrayLists. That's why you get a compiler error: Object doesn't have a method named get().
To fix the problem, you need to use generics:
ArrayList<List<Integer>> main = new ArrayList<>();
ArrayList<Integer> sub=new ArrayList<>();
Now get() will return a List<Integer> which has a get() method, so the compiler error will disappear.
Generics could be your friend here:
ArrayList<ArrayList<Object>> main = new ArrayList<ArrayList<Object>>(); // or new ArrayList<>(); in Java 7+
ArrayList<Object> sub = new ArrayList<Object>(); // or new ArrayList<>();
If you can't or don't want to use generics, the solution is to cast the expression main.get(i) to an ArrayList first:
System.out.println(((ArrayList) main.get(i)).get(j));
Go through the following code
public class ArrayListDemo {
public static void main(String[] args) {
List<List<Integer>> main = new ArrayList<>();
List<Integer> sub = new ArrayList<>();
sub.add(1);
sub.add(2);
main.add(sub);
//If you want to get values in sub array list
for(int i = 0; i < 1; i++){
List<Integer> arr = main.get(i);
for(Integer val : arr) System.out.println(val + "");
}
//If you want to print all values
for(List<Integer> list : main){
for(Integer val : list) System.out.println(val + "");
}
}
}
In the above code, I had declared an ArrayList (main) to keep all Array which are having Integer values. Also i had declared an another ArrayList (sub) to keep all Integer values.
I had used ArrayList data structure because of length of the List will be changing the
run time.
Good Luck !!!

How to remove multiple elements in Vector in Java?

I read from .txt file all of the ids and insert these ids into Vector.
String pathSelectedfile = fileChooser.getSelectedFile().getAbsolutePath();
File selectedFile = new File(pathSelectedfile);
Scanner readFile = new Scanner(selectedFile);
Vector ids=new Vector();
while (readFile.hasNextLine()) {
String id= readFile.nextLine();
ids.addElement(id);
}
then I want to remove multiple ids in Vector.i can do that by for loop
but information is too big.tnx a lot
To remove multiple values
Vector vector = new Vector();
vector.add("value1");
vector.add("value2");
vector.add("value3");
vector.add("value4");
System.out.println("Size : "+vector.size());
// to remove single value
vector.remove("value1");
System.out.println("Size : "+vector.size());
Vector itemsToRemove = new Vector();
itemsToRemove.add("value3");
itemsToRemove.add("value4");
//remove multiple values
vector.removeAll(itemsToRemove);
System.out.println("Size : "+vector.size());
//to remove all elements
vector.removeAllElements();
// or
vector.clear();
But instead of using Vector consider to use ArrayList since Vector is obsolete collection.
Read this : Why is Java Vector class considered obsolete or deprecated?
Also use generics Like ArrayList<String> idList = new ArrayList() if you store only String elements in list.
If you want to skip duplicates when adding elements in Vector, use the following code
Vector vector = new Vector() {
#Override
public synchronized boolean add(Object e) {
if(!contains(e)){
return super.add(e);
}
System.out.println("Element " + e +" is duplicate");
return false ;
}
};
But if you want to add only unique elements, use Set
Do completely remove the duplicated ids, you could use the following:
Set<String> ids=new LinkedHashSet<String>();
Set<String> duplicates=new HashSet<String>();
while (readFile.hasNextLine()) {
String id= readFile.nextLine();
if(!ids.add(id)) {
duplicates.add(id);
}
}
ids.removeAll(duplicates)
Note that unlike Vector, LinkedHashSet is not synchronized. In most cases this is not a bad thing, but in the case that you actually need it to be synchronized, wrap it using Collections.synchronizedSet()
READ the javadoc and pay attention to methods starting with remove http://docs.oracle.com/javase/6/docs/api/java/util/Vector.html. This should be you first approach not SO.
If you "want to remove multiple ids in Vector" do the following
ids = new Vector(new HashSet(ids))

removing duplicates from list of lists and preserving lists

I have an arrayList of arrayLists. Each inner arraylist contains some objects with the format (name.version) .
{ {a.1,b.2,c.3} , {a.2,d.1,e.1} , {b.3,f.1,z.1}....}
For example a.1 implies name = a and version is 1.
So i want to eliminate duplicates in this arraylist of lists. For me , two objects are duplicate when they have the same name
So essentially my output should be
{ { a.1,b.2,c.3},{d.1,e.1} ,{f.1 ,z.1} }
Note that i want the output in the exact same form (That is , i dont want a single list with no duplicates)
Can someone provide me with an optimal solution for this?
I can loop through each inner list and place the contents in the hashset. But two issues there, i cant get back the answer in
form of list of lists.Another issue is that when i need to override equals for that object , but i am not sure if that would
break other code. These objects are meaningfully equal if their names are same (only in this case. I am not sure that would
cover the entire spectrum)
Thanks
I used Iterator.remove() to modify the collection as you move through it.
// build your example input as ArrayList<ArrayList<String>>
String[][] tmp = { { "a.1", "b.2", "c.3" }, { "a.2", "d.1", "e.1" },
{ "b.3", "f.1", "z.1" } };
List<List<String>> test = new ArrayList<List<String>>();
for (String[] array : tmp) {
test.add(new ArrayList<String>(Arrays.asList(array)));
}
// keep track of elements we've already seen
Set<String> nameCache = new HashSet<String>();
// iterate and remove if seen before
for (List<String> list : test) {
for (Iterator<String> it = list.iterator(); it.hasNext();) {
String element = it.next();
String name = element.split("\\.")[0];
if (nameCache.contains(name)) {
it.remove();
} else {
nameCache.add(name);
}
}
}
System.out.println(test);
Output
[[a.1, b.2, c.3], [d.1, e.1], [f.1, z.1]]
List<List<Pair>> inputs; // in whatever format you have them
List<List<Pair>> uniqued = new ArrayList<>(); // output to here
Set<String> seen = new HashSet<String>();
for (List<Pair> list : inputs) {
List<Pair> output = new ArrayList<>();
for (Pair p : list)
if (seen.add(p.getName()))
output.add(p);
uniqued.add(output);
}
Create a Set. Iterate over the list of lists' items. See if the item is in the Set. If it is already there, ignore it. If it isn't, add it to the Set and the list of lists.
Your method will return a new list of lists, not modify the old one. Modifying a list while iterating over it is a pain.

Categories