How to convert SetString to String[]?
Use the Set#toArray(IntFunction<T[]>)
method taking an IntFunction
as generator.
String[] GPXFILES1 = myset.toArray(String[]::new);
If you're not on Java 11 yet, then use the Set#toArray(T[])
method taking a typed array argument of the same size.
String[] GPXFILES1 = myset.toArray(new String[myset.size()]);
While still not on Java 11, and you can't guarantee that myset
is unmodifiable at the moment of conversion to array, then better specify an empty typed array.
String[] GPXFILES1 = myset.toArray(new String[0]);
Fastest way to put contents of SetString to a single String with words separated by a whitespace?
With commons/lang you can do this using StringUtils.join:
String str_1 = StringUtils.join(set_1, " ");
You can't really beat that for brevity.
Update:
Re-reading this answer, I would prefer the other answer regarding Guava's Joiner now. In fact, these days I don't go near apache commons.
Another Update:
Java 8 introduced the method String.join()
String joined = String.join(",", set);
While this isn't as flexible as the Guava version, it's handy when you don't have the Guava library on your classpath.
Convert set to string and vice versa
Use repr
and eval
:
>>> s = set([1,2,3])
>>> strs = repr(s)
>>> strs
'set([1, 2, 3])'
>>> eval(strs)
set([1, 2, 3])
Note that eval
is not safe if the source of string is unknown, prefer ast.literal_eval
for safer conversion:
>>> from ast import literal_eval
>>> s = set([10, 20, 30])
>>> lis = str(list(s))
>>> set(literal_eval(lis))
set([10, 20, 30])
help on repr
:
repr(object) -> string
Return the canonical string representation of the object.
For most object types, eval(repr(object)) == object.
How to convert SetSetString to SetString?
Here is the option using Stream API:
Set<String> result = sets.stream()
.flatMap(Collection::stream)
.collect(Collectors.toSet());
How to convert String to string set in java
I use Apache Commons for string manipulation. Following code helps.
String substringBetween = StringUtils.substringBetween(str, "[", "]").replaceAll("\"", ""); // get rid of bracket and quotes
String[] csv = StringUtils.split(substringBetween,","); // split by comma
Set<String> columnmapping = new HashSet<String>(Arrays.asList(csv));
Convert SetV to MapString, SetString
Replace
Collectors.toSet(Pair::getValue)
with
Collectors.mapping(Pair::getValue, Collectors.toSet())
The problem is that Collectors.toSet()
doesn't have any parameters, it operates on the type defined by the input stream. Collectors.mapping(mapper, downstream)
alters this behaviour by "applying a mapping function to each input element before accumulation".
How do I turn a SetString into a string in Java?
If you're using Java 8 or later, then String#join
is one option. However, you should use an ordered collection to ensure that the strings appear in the order you want:
List<String> myList = Arrays.asList(new String[] { "how", "are", "you" });
String output = String.join(":*|", myList) + ":*";
System.out.println(output); // how:*|are:*|you:*
You have revealed that you are trying to build a regex alternation to search for a term in your database. If so, then you should be using this pattern:
.*\b(?:how:|are:|you:).*
The leading and trailing .*
might be optional, in the case where the API accepts a pattern matching just a portion of the column. Here is the updated Java code to generate this pattern:
List<String> myList = Arrays.asList(new String[] { "how", "are", "you" });
StringBuilder sb = new StringBuilder();
sb.append(".*\\b(?:").append(String.join(":|", myList)).append(":).*");
System.out.println(sb.toString); // .*\b(?:how:|are:|you:).*
How to convert Set to string with space?
You can use Array.from
:
Array.from(foo).join(' ')
or the spread syntax:
[...foo].join(' ')
Java: How to convert String[] to List or Set
Arrays.asList() would do the trick here.
String[] words = {"ace", "boom", "crew", "dog", "eon"};
List<String> wordList = Arrays.asList(words);
For converting to Set, you can do as below
Set<T> mySet = new HashSet<T>(Arrays.asList(words));
How to convert SetString to SetObject
With streams:
Set<Role> convertStringSetToRoleSetWithStreams(final Set<String> rolesInString) {
return rolesInString.stream().map(roleInString -> {
final Role role = new Role();
role.setName(ERole.valueOf(roleInString));
return role;
}).collect(Collectors.toSet());
}
Without streams:
Set<Role> convertStringSetToRoleSetWithoutStreams(final Set<String> rolesInString) {
final Set<Role> rolesInObject = new HashSet<>();
for (final String roleInString : rolesInString) {
final Role role = new Role();
role.setName(ERole.valueOf(roleInString));
rolesInObject.add(role);
}
return rolesInObject;
}
Feel free to accept the answer if it works.
Related Topics
Why Does This Gridbaglayout Not Appear as Planned
Hibernate - Foreign Keys Instead of Entities
JSON Gson.Fromjson Java Objects
How Does Java Object Casting Work Behind the Scene
Eclipse Will Not Open Due to Environment Variables
Threads Configuration Based on No. of Cpu-Cores
Is Doing a Lot in Constructors Bad
Why Is My Jlabel Not Showing Up
Is There a Method That Calculates a Factorial in Java
How to Use Readline() Method in Java
How to Use a Java8 Lambda to Sort a Stream in Reverse Order
Extract Source Code from .Jar File
Sharing a Persistence Unit Across Components in a .Ear File
Guessing the Encoding of Text Represented as Byte[] in Java
Is It Bad Practice to Use Reflection in Unit Testing
Import Sun.Misc.Base64Encoder Results in Error Compiled in Eclipse