How to convert a String[] into a set? [duplicate] - java

This question already has answers here:
Java: How to convert String[] to List or Set [duplicate]
(9 answers)
Closed 9 years ago.
I did this:
Set<String> mySet = new TreeSet<String>();
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
mySet.addAll(wordArr);
This gives error:
The method addAll(Collection<? extends String>) in the type Set<String> is
not applicable for the arguments (String[])
I think my intentions are clear.
Side ques: is there a better way to achieve my desired set? I know already there are no repeated value in my list.

The TreeSet constructor accepts a Collection, a String[] can be converted to a List which implements Collection using Arrays.asList().
public static void main(String[] args) {
String list = "word,another,word2"; //No need for () here
String[] wordArr = list.split(",");
Set<String> mySet = new TreeSet<String>(Arrays.asList(wordArr));
for(String s:mySet){
System.out.println(s);
}
}

Here's an example using Guava:
package com.sandbox;
import com.google.common.collect.Sets;
import java.util.Set;
public class Sandbox {
public static void main(String[] args) {
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
Set<String> mySet = Sets.newHashSet(wordArr);
}
}
If you want to do this without Arrays (I don't recommend, but you're in a class so maybe you can't use it):
package com.sandbox;
import java.util.Set;
import java.util.TreeSet;
public class Sandbox {
public static void main(String[] args) {
Set<String> mySet = new TreeSet<String>();
String list = ("word,another,word2"); // actually this is much bigger
String[] wordArr = list.split(",");
for (String s : wordArr) {
mySet.add(s);
}
}
}

Related

How iterate an ArrayList inside various others ArrayLists?

I was notified that is possible to create "infinite" ArrayLists inside others, such as in the code below:
import java.util.ArrayList;
public class Main
{
public static void main(String[] args) {
ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<Object>>>>> List = new ArrayList<ArrayList<ArrayList<ArrayList<ArrayList<Object>>>>>();
}
}
And I want know about how to iterate them (with foreach or other loop types)
You could try to traverse it like a composite:
public static void traverse(ArrayList<T> arg) {
arg.forEach(
(n) -> if (n instanceof ArrayList) {
traverse(n)
} else {
doStomething(n)
}
);
}
IMHO, if someone writes such structures - it's some kind of a maniac.
But still, you can follow this kind of pattern in order to traverse:
#Test
public void test4() {
List<String> list1 = new ArrayList<>();
list1.add("abc");
list1.add("def");
List<List<String>> list2 = new ArrayList<>();
list2.add(list1);
list2.stream().flatMap(Collection::stream).forEach(System.out::println);
}
```

JAVA Dictionary as parameter [duplicate]

This question already has answers here:
What does it mean to "program to an interface"?
(33 answers)
Closed 3 years ago.
Now I got a dictionary like this
Dictionary dict = new Hashtable();
dict.put("shipno", item.getShipNumber());
dict.put("addr", item.getFinalAddr());
dict.put("receiver", item.getReceiverName());
dict.put("phone", item.getReceiverPhone());
and I'm going to pass this dictionary to funcion Test() as a parameter, what should I put in the '()'
public static int Test(Dictionary)
Is this correct? Thanks!
In your code you have to call this method:
Dictionary dict = new Hashtable();
dict.put("shipno", item.getShipNumber());
// CAll THIS METHOD
Test(dict);
And in your method you can get this data:
// YOUR METHOD, where "dict" is passed argument/parameter
public static int Test(Dictionary dict) {
}
Its working here
import java.util.Dictionary;
import java.util.Enumeration;
import java.util.Hashtable;
public class Dict {
public static void main(String[] args) {
Dictionary<String, String> obj = new Hashtable<String, String>();
obj.put("Hello", "World");
obj.put("Hello1", "World3");
obj.put("Hello2", "World32");
Dict ca = new Dict();
ca.test(obj);
}
public void test(Dictionary<String, String> obj) {
Enumeration<String> enumData = obj.elements();
while (enumData.hasMoreElements()) {
System.out.println(enumData.nextElement());
}
}
}

Java: For loop on Objects of Strings

I'm new in Java and I have to solve this exercise. I have this code:
public class StringList {
private String list = "";
public StringList(String... str) {
for (String s : str) list += s+"\t";
}
}
and I have to change the class so that its objects allow the iteration by using this instruction:
for (String s : new StringList("a", "b", "c")) System.out.println(s);
My idea was to create a List and iterate on it. So I changed the code in this way:
public class StringList {
private List<String> list = new ArrayList<String>();
public StringList(String... str) {
for (String s: str) list.add(s);
}
}
but when I try the iteration with the above instruction I get this error (Can only iterate over an array or an instance of java.lang.Iterable) and I spent hours trying to fix it but I keep failing. Any help?
To do it the clean way, give a look at the java.lang.Iterable interface : https://docs.oracle.com/javase/8/docs/api/java/lang/Iterable.html
If your StringList class implements it, then the instruction will work. I'll let you complete the exercise yourself though, but you can start with
public class StringList implements Iterable<String> {
// the attribute you need to store the strings object
// your constructor
#Override
public Iterator<String> iterator() {
// This is what you need to fill
}
}
PS : Using a list of string as an attribute is not a bad idea at all and will save you a lot of efforts and time, search what you can do with it
You have to implement Iterable<String> to your StringList like this:
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Spliterator;
import java.util.function.Consumer;
public class StringList implements Iterable<String> {
private List<String> list = new ArrayList<String>();
public StringList(String... str) {
for (String s: str) { list.add(s); }
}
#Override
public Iterator<String> iterator() {
return list.iterator();
}
#Override
public void forEach(Consumer<? super String> action) {
list.forEach(action);
}
#Override
public Spliterator<String> spliterator() {
return list.spliterator();
}
}

How to pass Java List to Scala, filter it in Scala and get back to Java?

For example:
package example.javascala.list;
import java.util.Arrays;
import java.util.List;
public class UseScalaList {
public static void main(String[] args) {
String[] words = {"a", "very", "long", "list", "of", "words"};
List<String> lst = Arrays.asList(words);
// Call Scala code here to filter word "a" from Java list and return back List<String> ?
}
}
Questions:
Scala object to filter java.util.List<String>
How to call Scala and get filtered list back?
Try this:
import scala.collection.*;
Collection<String> filtered = JavaConversions.asJavaCollection(JavaConversions.asScalaIterable(lst).filter(...));
UPDATE:
Iterable<String> scalaIterable = JavaConversions.asScalaIterable(lst);
scalaIterable.filter(...);
scalaIterable.drop(1);
scalaIterable.somethingMore(...);
Collection<String> backToJava = JavaConversions.asJavaCollection(scalaIterable);

Java Android Arraylist string to ArrayList custom class

How can I convert values here:
List<String> values = new ArrayList<String>
to :
ArrayList<Custom>
EDIT:
public class Custom {
public Custom Parse(String input) {
// What should I do here?
}
}
You could use:
List<Custom> customList = new ArrayList<Custom>();
for (String value: values) {
customList.add(new Custom(value));
}
Although it would be better just to add a constructor with a String argument:
class Custom {
private final String input;
public Custom(String input) {
this.input = input;
}
// not needed but implemented for completeness
public static Custom parse(String input) {
return new Custom(input);
}
}
Assuming your list of Custom objects has the same size with values list.
With one enhanced for-loop, set the appropriate fields of your objects like this:
int i=0;
for(String str:values)
customList.get(i++).setSomeProperty(str);
you can find a solution using Google Collections libraries on this thread Converting a List<String> to a List<Integer> (or any class that extends Number)

Categories