Getting an element from a Set
There would be no point of getting the element if it is equal. A Map
is better suited for this usecase.
If you still want to find the element you have no other option but to use the iterator:
public static void main(String[] args) {
Set<Foo> set = new HashSet<Foo>();
set.add(new Foo("Hello"));
for (Iterator<Foo> it = set.iterator(); it.hasNext(); ) {
Foo f = it.next();
if (f.equals(new Foo("Hello")))
System.out.println("foo found");
}
}
static class Foo {
String string;
Foo(String string) {
this.string = string;
}
@Override
public int hashCode() {
return string.hashCode();
}
@Override
public boolean equals(Object obj) {
return string.equals(((Foo) obj).string);
}
}
How to get first item from a java.util.Set?
From the Oracle docs:
As implied by its name, this interface models the mathematical set abstraction.
In Set Theory, "a "set" is a collection of distinct objects, considered as an object in its own right." - [Wikipedia - Set].
Mathematically, elements in sets are not individualised. Their only identity is derived from their presence in the set. Therefore, there is no point in getting the "first" element in a set, as conceptually such a task is illogical.
There may be no point to getting the "first" element from a set, but if all you need is to get one single object from a set (with no guarantees as to which object that is) you can do the following:
for(String aSiteId: siteIdSet) {
siteId = aSiteId;
break;
}
This is a slightly shorter way (than the method you posted) to get the "first" object of a Set
, however since an Iterator is still being created (under the hood) it does not grant any performance benefit.
How to retrieve an element from a set without removing it?
Two options that don't require copying the whole set:
for e in s:
break
# e is now an element from s
Or...
e = next(iter(s))
But in general, sets don't support indexing or slicing.
Good way to get *any* value from a Java Set?
A Set<T>
is an Iterable<T>
, so iterating to the first element works:
Set<T> things = ...;
return things.iterator().next();
Guava has a method to do this, though the above snippet is likely better.
Get the other element from a set (Python)
This answer addresses the particular question of how to access one element of a (two-element) set, given the other element.
If you're using a set, you can use the set difference operator, then your method of choice to get the sole element of a set (the first bit is identical to the answer you linked):
options = {'a', 'b'}
other = options - {'a'} # b is {'b'}
# A few ways to get the sole element of a set
b = next(iter(other))
b = min(other) # or max
b, = other # or "[b] = other"
The last method for extracting the sole element of a set also raises an exception if the set has multiple elements.
If you don't mind destroying the list of possible values (i.e. if you already are using a copy), you can remove
or discard
1 the value you don't want, then pop
the remaining value.
options = {'a', 'b'}
options.remove('a')
value = options.pop()
# options is now empty, and value is 'b'
In general, to understand sets, I'd start by reading the documentation.
1 remove
raises an exception if the element is missing; discard
does not
Java: Get first item from a collection
Iterables.get(yourC, indexYouWant)
Because really, if you're using Collections, you should be using Google Collections.
The most efficient method to find an element in Set
Because TreeSet
is a NavigableSet
, you can use TreeSet.subSet
, which leverages knowledge about the order of the elements to extract a range of elements as close as possible to the element you are interested in:
Person pattern = new Person(id);
return
// Get the Persons between pattern (inclusive) and pattern (inclusive).
// In other words: all the Persons with id equal to the input,
// of which there are zero or one.
idTreeSet.subSet(pattern, true, pattern, true).stream()
.findFirst()
.orElse(null);
Get the only element in a Set
Your question asks to get something from the Set. But your example just needs a check.
If you know what to expect in the Set, this works fine.
if (enabled != null && enabled.size() == 1 && enabled.contains("true")) {
...
}
Otherwise, if you just want to get the element but don't know what it is, the iterator you suggested works fine.
String getOnlyElement(Set<String> enabled, String default) {
return (enabled == null || enabled.size() != 1) ? default : enabled.iterator().next();
}
I like having null checks but it depends on what methodToGetValues returns.
How to write to an Element in a Set?
You are getting the error because columns
might be a set of struct
. So columns.first
will give you an immutable value. If you were to use a class
, you will get a mutable result from columns.first
and your code will work as expected.
Otherwise, you will have to do as explained by @Sweeper in his answer.
Related Topics
Providing Input/Subcommands to Command Executed Over Ssh with Jsch
How to Write Logs in Text File When Using Java.Util.Logging.Logger
How to Convert Ascii Code (0-255) to Its Corresponding Character
How to Call the Overridden Method of a Superclass
How to Simulate Keyboard Presses in Java
Java:Non-Static Variable Cannot Be Referenced from a Static Context Error
How to Make Java Honor the Dns Caching Timeout
Can You Split a Stream into Two Streams
Assert Equals Between 2 Lists in Junit
Change Background Color of One Cell in Jtable
Jpa: How to Have One-To-Many Relation of the Same Entity Type
Is Httpsession Thread Safe, Are Set/Get Attribute Thread Safe Operations
How Is Hashcode() Calculated in Java
Package Conflicts with Automatic Modules in Java 9
Applying Map of the Earth Texture a Sphere
Default Values and Initialization in Java
Retrieving the Inherited Attribute Names/Values Using Java Reflection