Java Code Examples for java.util.AbstractMap

The following are top voted examples for showing how to use java.util.AbstractMap. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: firebase-admin-java   File: ArraySortedMap.java   Source Code and License 8 votes vote down vote up
private Iterator<Map.Entry<K, V>> iterator(final int pos, final boolean reverse) {
  return new Iterator<Map.Entry<K, V>>() {
    int currentPos = pos;

    @Override
    public boolean hasNext() {
      return reverse ? currentPos >= 0 : currentPos < keys.length;
    }

    @Override
    public Map.Entry<K, V> next() {
      final K key = keys[currentPos];
      final V value = values[currentPos];
      currentPos = reverse ? currentPos - 1 : currentPos + 1;
      return new AbstractMap.SimpleImmutableEntry<>(key, value);
    }

    @Override
    public void remove() {
      throw new UnsupportedOperationException("Can't remove elements from ImmutableSortedMap");
    }
  };
}
 
Example 2
Project: joal   File: BitTorrentClientConfigTest.java   Source Code and License 6 votes vote down vote up
@Test
public void shouldBuildClient() {
    final String query = "info_hash={infohash}&peer_id={peerid}&supportcrypto=1&port={port}&azudp={port}&uploaded={uploaded}&downloaded={downloaded}&left={left}&corrupt=0&event={event}&numwant={numwant}&no_peer_id=1&compact=1&key={key}&azver=3";
    final List<BitTorrentClientConfig.HttpHeader> requestHeaders = Arrays.asList(
            new HttpHeader("User-Agent", "Azureus 5.7.5.0;{os};1.8.0_66"),
            new HttpHeader("Connection", "close"),
            new HttpHeader("Accept-Encoding", "gzip"),
            new HttpHeader("Accept", "text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2")
    );

    final PeerIdGenerator peerIdGenerator = PeerIdGeneratorTest.createDefault();
    final KeyGenerator keyGenerator = KeyGeneratorTest.createDefault();
    final BitTorrentClientConfig config = new BitTorrentClientConfig(peerIdGenerator, query, keyGenerator, defaultUrlEncoder, requestHeaders, 200, 0);

    final BitTorrentClient client = config.createClient();
    assertThat(client.getHeaders()).isEqualTo(requestHeaders.stream()
            .map(header -> new AbstractMap.SimpleEntry<>(header.getName(), header.getValue()))
            .collect(Collectors.toList())
    );
    assertThat(client.getQuery()).isEqualTo(query);
    //noinspection OptionalGetWithoutIsPresent
    assertThat(client.getKey(null, RequestEvent.STARTED).get()).isEqualTo(keyGenerator.getKey(null, RequestEvent.STARTED));
    assertThat(client.getPeerId(null, RequestEvent.STARTED)).isEqualTo(peerIdGenerator.getPeerId(null, RequestEvent.STARTED));
    assertThat(client.getNumwant(RequestEvent.STARTED)).isEqualTo(200);
}
 
Example 3
Project: openjdk-jdk10   File: ConcurrentSkipListMap.java   Source Code and License 6 votes vote down vote up
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
    if (action == null) throw new NullPointerException();
    Comparator<? super K> cmp = comparator;
    K f = fence;
    Node<K,V> e = current;
    current = null;
    for (; e != null; e = e.next) {
        K k; Object v;
        if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
            break;
        if ((v = e.value) != null && v != e) {
            @SuppressWarnings("unchecked") V vv = (V)v;
            action.accept
                (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
        }
    }
}
 
Example 4
Project: incubator-netbeans   File: ModesSubModel.java   Source Code and License 6 votes vote down vote up
public Set<ModeStructureSnapshot.SlidingModeSnapshot> createSlidingModeSnapshots() {
    Set<ModeStructureSnapshot.SlidingModeSnapshot> result = 
            new HashSet<ModeStructureSnapshot.SlidingModeSnapshot>();
    for (Map.Entry<ModeImpl, String> curEntry: slidingModes2Sides.entrySet()) {
        final ModeImpl key = curEntry.getKey();
        AbstractMap<TopComponent, Integer> lazy = new AbstractMap<TopComponent, Integer>() {
            Map<TopComponent, Integer> delegate;
            @Override
            public Set<Entry<TopComponent, Integer>> entrySet() {
                if (delegate == null) {
                    delegate = getSlideInSizes(key);
                }
                return delegate.entrySet();
            }
        };

         result.add(new ModeStructureSnapshot.SlidingModeSnapshot(
                curEntry.getKey(), curEntry.getValue(), lazy
        ));
    }
    return result;
}
 
Example 5
Project: JRediClients   File: CommandAsyncService.java   Source Code and License 6 votes vote down vote up
private <T> T tryHandleReference0(T o) {
    if (o instanceof RedissonReference) {
        return fromReference(o);
    } else if (o instanceof ScoredEntry && ((ScoredEntry) o).getValue() instanceof RedissonReference) {
        ScoredEntry<?> se = ((ScoredEntry<?>) o);
        return (T) new ScoredEntry(se.getScore(), fromReference(se.getValue()));
    } else if (o instanceof ScanObjectEntry) {
        ScanObjectEntry keyScan = (ScanObjectEntry) o;
        Object obj = tryHandleReference0(keyScan.getObj());
        return obj != keyScan.getObj() ? (T) new ScanObjectEntry(keyScan.getBuf(), obj) : o;
    } else if (o instanceof Map.Entry) {
        Map.Entry old = (Map.Entry) o;
        Object key = tryHandleReference0(old.getKey());
        Object value = tryHandleReference0(old.getValue());
        return value != old.getValue() || key != old.getKey()
                ? (T) new AbstractMap.SimpleEntry(key, value)
                : o;
    } else {
        return o;
    }
}
 
Example 6
Project: openjdk-jdk10   File: ResponderIdTests.java   Source Code and License 6 votes vote down vote up
@Override
public Map.Entry<Boolean, String> runTest() {
    Boolean pass = Boolean.FALSE;
    String message = null;
    try {
        ResponderId ridByKeyIdBytes =
                new ResponderId(INV_EXPLICIT_TAG_KEY_ID);
        throw new RuntimeException("Expected IOException not thrown");
    } catch (IOException ioe) {
        // Make sure it's the IOException we're looking for
        if (ioe.getMessage().contains("Invalid ResponderId content")) {
            pass = Boolean.TRUE;
        } else {
            ioe.printStackTrace(System.out);
            message = ioe.getClass().getName();
        }
    } catch (Exception e) {
        e.printStackTrace(System.out);
        message = e.getClass().getName();
    }

    return new AbstractMap.SimpleEntry<>(pass, message);
}
 
Example 7
Project: jdk8u-jdk   File: ConcurrentSkipListMap.java   Source Code and License 6 votes vote down vote up
/**
 * Submap version of ConcurrentSkipListMap.getNearEntry
 */
Map.Entry<K,V> getNearEntry(K key, int rel) {
    Comparator<? super K> cmp = m.comparator;
    if (isDescending) { // adjust relation for direction
        if ((rel & LT) == 0)
            rel |= LT;
        else
            rel &= ~LT;
    }
    if (tooLow(key, cmp))
        return ((rel & LT) != 0) ? null : lowestEntry();
    if (tooHigh(key, cmp))
        return ((rel & LT) != 0) ? highestEntry() : null;
    for (;;) {
        Node<K,V> n = m.findNear(key, rel, cmp);
        if (n == null || !inBounds(n.key, cmp))
            return null;
        K k = n.key;
        V v = n.getValidValue();
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}
 
Example 8
Project: airgram   File: MessageObject.java   Source Code and License 6 votes vote down vote up
public CharSequence replaceWithLink(CharSequence source, String param, ArrayList<Integer> uids, AbstractMap<Integer, TLRPC.User> usersDict) {
    int start = TextUtils.indexOf(source, param);
    if (start >= 0) {
        SpannableStringBuilder names = new SpannableStringBuilder("");
        for (int a = 0; a < uids.size(); a++) {
            TLRPC.User user = null;
            if (usersDict != null) {
                user = usersDict.get(uids.get(a));
            }
            if (user == null) {
                user = MessagesController.getInstance().getUser(uids.get(a));
            }
            if (user != null) {
                String name = UserObject.getUserName(user);
                start = names.length();
                if (names.length() != 0) {
                    names.append(", ");
                }
                names.append(name);
                names.setSpan(new URLSpanNoUnderlineBold("" + user.id), start, start + name.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
        return TextUtils.replace(source, new String[]{param}, new CharSequence[]{names});
    }
    return source;
}
 
Example 9
Project: openjdk-jdk10   File: ConcurrentSkipListMap.java   Source Code and License 6 votes vote down vote up
/**
 * Submap version of ConcurrentSkipListMap.getNearEntry.
 */
Map.Entry<K,V> getNearEntry(K key, int rel) {
    Comparator<? super K> cmp = m.comparator;
    if (isDescending) { // adjust relation for direction
        if ((rel & LT) == 0)
            rel |= LT;
        else
            rel &= ~LT;
    }
    if (tooLow(key, cmp))
        return ((rel & LT) != 0) ? null : lowestEntry();
    if (tooHigh(key, cmp))
        return ((rel & LT) != 0) ? highestEntry() : null;
    for (;;) {
        Node<K,V> n = m.findNear(key, rel, cmp);
        if (n == null || !inBounds(n.key, cmp))
            return null;
        K k = n.key;
        V v = n.getValidValue();
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}
 
Example 10
Project: elasticsearch_my   File: JvmGcMonitorServiceSettingsTests.java   Source Code and License 6 votes vote down vote up
public void testMissingSetting() throws InterruptedException {
    String collector = randomAsciiOfLength(5);
    Set<AbstractMap.SimpleEntry<String, String>> entries = new HashSet<>();
    entries.add(new AbstractMap.SimpleEntry<>("monitor.jvm.gc.collector." + collector + ".warn", randomPositiveTimeValue()));
    entries.add(new AbstractMap.SimpleEntry<>("monitor.jvm.gc.collector." + collector + ".info", randomPositiveTimeValue()));
    entries.add(new AbstractMap.SimpleEntry<>("monitor.jvm.gc.collector." + collector + ".debug", randomPositiveTimeValue()));
    Settings.Builder builder = Settings.builder();

    // drop a random setting or two
    for (@SuppressWarnings("unchecked") AbstractMap.SimpleEntry<String, String> entry : randomSubsetOf(randomIntBetween(1, 2), entries.toArray(new AbstractMap.SimpleEntry[0]))) {
        builder.put(entry.getKey(), entry.getValue());
    }

    // we should get an exception that a setting is missing
    execute(builder.build(), (command, interval, name) -> null, e -> {
        assertThat(e, instanceOf(IllegalArgumentException.class));
        assertThat(e.getMessage(), containsString("missing gc_threshold for [monitor.jvm.gc.collector." + collector + "."));
    }, true, null);
}
 
Example 11
Project: VillagerTrades   File: VillagerRegistryHelper.java   Source Code and License 6 votes vote down vote up
public static List<Map.Entry<Integer, String>> getProfessionIdsAndNamesSortedById()
{
	List<Map.Entry<Integer, String>> professions = new ArrayList<Map.Entry<Integer, String>>();

	for (VillagerRegistry.VillagerProfession profession : ForgeRegistries.VILLAGER_PROFESSIONS.getValues())
	{
		@SuppressWarnings("deprecation")
		int id = VillagerRegistry.getId(profession);
		String name = profession.getRegistryName().toString();
		professions.add(new AbstractMap.SimpleEntry<Integer, String>(id, name));
	}

	Collections.sort(professions, new Comparator<Map.Entry<Integer, String>>()
	{
		@Override
		public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2)
		{
			return o1.getKey() - o2.getKey();
		}
	});

	return professions;

}
 
Example 12
Project: Supreme-Bot   File: SQLUtil.java   Source Code and License 6 votes vote down vote up
public static final <T> List<Map.Entry<Field, SQLField>> getFields(Class<? extends T> clazz, FieldType fieldType) {
    if (clazz == null || !clazz.isAnnotationPresent(SQLTable.class) || fieldType == null) {
        return new ArrayList<>();
    }
    return Arrays.asList(clazz.getFields()).stream().filter((field) -> field.isAnnotationPresent(SQLField.class)).map((field) -> new AbstractMap.SimpleEntry<>(field, field.getAnnotation(SQLField.class))).filter((field) -> {
        switch (fieldType) {
            case NONE:
                return false;
            case SEND:
                return field.getValue().send();
            case RECEIVE:
                return field.getValue().receive();
            case REMOVE:
                return field.getValue().primaryKey();
            case ALL:
                return true;
            default:
                return false;
        }
    }).sorted((field_1, field_2) -> field_1.getValue().index() - field_2.getValue().index()).collect(Collectors.toList());
}
 
Example 13
Project: fpc   File: Notifier.java   Source Code and License 6 votes vote down vote up
/**
  * Issue a DPN Availability Notification
  * @param dpnAvailability - DPN
  */
 static public void issueDpnAvailabilityNotification(DpnAvailability dpnAvailability){
 	for(ClientIdentifier clientId : FpcServiceImpl.clientIdList){
 		Long notificationId = NotificationInfo.next();
         Notify notif = new NotifyBuilder()
                 .setNotificationId(new NotificationId(notificationId))
                 .setTimestamp(BigInteger.valueOf(System.currentTimeMillis()))
                 .setValue(dpnAvailability)
                 .build();
         String streamString = fpcCodecUtils.notificationToJsonString(Notify.class,
        (DataObject) notif,
        true);
         streamString = streamString.replace("\n", "");
         streamString = "event:application/json;/notification\ndata:"+streamString+"\n";

         try {
	NotificationService.blockingQueue.put(new AbstractMap.SimpleEntry<String,String>(clientId.getInt64().toString(),streamString));
} catch (InterruptedException e) {
	ErrorLog.logError(e.getLocalizedMessage(),e.getStackTrace());
}
 	}
 }
 
Example 14
Project: googles-monorepo-demo   File: MapTestSuiteBuilderTests.java   Source Code and License 6 votes vote down vote up
private static Test testsForHashMapNullValuesForbidden() {
  return wrappedHashMapTests(new WrappedHashMapGenerator() {
    @Override Map<String, String> wrap(final HashMap<String, String> map) {
      if (map.containsValue(null)) {
        throw new NullPointerException();
      }
      return new AbstractMap<String, String>() {
        @Override public Set<Map.Entry<String, String>> entrySet() {
          return map.entrySet();
        }
        @Override public String put(String key, String value) {
          checkNotNull(value);
          return map.put(key, value);
        }
      };
    }
  }, "HashMap w/out null values", ALLOWS_NULL_KEYS);
}
 
Example 15
Project: hashsdn-controller   File: HardcodedModuleFactoriesResolver.java   Source Code and License 6 votes vote down vote up
public HardcodedModuleFactoriesResolver(final BundleContext bundleContext, final ModuleFactory... list) {
    this.factories = new HashMap<>(list.length);
    for (ModuleFactory moduleFactory : list) {
        String moduleName = moduleFactory.getImplementationName();
        if (moduleName == null || moduleName.isEmpty()) {
            throw new IllegalStateException("Invalid implementation name for " + moduleFactory);
        }
        Map.Entry<ModuleFactory, BundleContext> conflicting = factories.get(moduleName);
        if (conflicting == null) {
            factories.put(moduleName, new AbstractMap.SimpleEntry<>(moduleFactory, bundleContext));
        } else {
            throw new IllegalArgumentException(String.format(
                    "Module name is not unique. Found two conflicting factories with same name '%s':\n\t%s\n\t%s\n",
                    moduleName, conflicting.getKey(), moduleFactory));
        }
    }
}
 
Example 16
Project: jdk8u-jdk   File: ConcurrentSkipListMap.java   Source Code and License 6 votes vote down vote up
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
    if (action == null) throw new NullPointerException();
    Comparator<? super K> cmp = comparator;
    K f = fence;
    Node<K,V> e = current;
    current = null;
    for (; e != null; e = e.next) {
        K k; Object v;
        if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
            break;
        if ((v = e.value) != null && v != e) {
            @SuppressWarnings("unchecked") V vv = (V)v;
            action.accept
                (new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
        }
    }
}
 
Example 17
Project: openjdk-jdk10   File: ConcurrentHashMap.java   Source Code and License 6 votes vote down vote up
/**
 * Helper method for EntrySetView.removeIf.
 */
boolean removeEntryIf(Predicate<? super Entry<K,V>> function) {
    if (function == null) throw new NullPointerException();
    Node<K,V>[] t;
    boolean removed = false;
    if ((t = table) != null) {
        Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length);
        for (Node<K,V> p; (p = it.advance()) != null; ) {
            K k = p.key;
            V v = p.val;
            Map.Entry<K,V> e = new AbstractMap.SimpleImmutableEntry<>(k, v);
            if (function.test(e) && replaceNode(k, null, v) != null)
                removed = true;
        }
    }
    return removed;
}
 
Example 18
Project: guava-mock   File: MapTestSuiteBuilderTests.java   Source Code and License 6 votes vote down vote up
private static Test testsForHashMapNullValuesForbidden() {
  return wrappedHashMapTests(new WrappedHashMapGenerator() {
    @Override Map<String, String> wrap(final HashMap<String, String> map) {
      if (map.containsValue(null)) {
        throw new NullPointerException();
      }
      return new AbstractMap<String, String>() {
        @Override public Set<Map.Entry<String, String>> entrySet() {
          return map.entrySet();
        }
        @Override public String put(String key, String value) {
          checkNotNull(value);
          return map.put(key, value);
        }
      };
    }
  }, "HashMap w/out null values", ALLOWS_NULL_KEYS);
}
 
Example 19
Project: QuantTester   File: SinYeeBarInputStream.java   Source Code and License 6 votes vote down vote up
Map<String, Map.Entry<Integer, Integer>[]> getAvailableContracts() throws IOException {
	Map<String, Map.Entry<Integer, Integer>[]> available_contracts = new HashMap<>();
	short contract_num = readShort();
	for (int i = 0; i < contract_num; i++) {
		byte strlen = (byte) read();
		byte[] contract_name_bytes = new byte[strlen];
		read(contract_name_bytes, 0, strlen);
		String contract_name = new String(contract_name_bytes);

		skip(29 - strlen); // ����Unicode���contract_name

		@SuppressWarnings("unchecked")
		Map.Entry<Integer, Integer>[] offset_nums = new Map.Entry[8];
		for (int j = 0; j < 8; j++) {
			offset_nums[j] = new AbstractMap.SimpleEntry<>(readInt(), readInt());
		}
		available_contracts.put(contract_name, offset_nums);
	}
	return available_contracts;
}
 
Example 20
Project: swblocks-decisiontree   File: DecisionTreeRuleTest.java   Source Code and License 6 votes vote down vote up
@Test
public void testRuleDuplicateOutputCheck() {
    final DecisionTreeRule rule = new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input1", "input2"), Collections.singletonMap("outputDriver", "result"), null,
            null);
    assertTrue(rule.isDuplicateOutputData(new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input1", "input2"), Collections.singletonMap("outputDriver", "result"), null,
            null)));
    assertTrue(rule.isDuplicateOutputData(new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input3", "input4"), Collections.singletonMap("outputDriver", "result"), null,
            null)));
    assertFalse(rule.isDuplicateOutputData(null));
    assertFalse(rule.isDuplicateOutputData(new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input3", "input4"), Collections.singletonMap("outputDriver", "result1"), null,
            null)));
    assertFalse(rule.isDuplicateOutputData(new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(),
            getInputDriverArray("input3", "input4"), Collections.singletonMap("outputDriver1", "result1"), null,
            null)));
    assertFalse(rule.isDuplicateOutputData(
            new DecisionTreeRule(new UUID(0, 1), UUID.randomUUID(), getInputDriverArray("input3", "input4"),
                    Stream.of(new AbstractMap.SimpleEntry<>("outputDriver", "result1"),
                            new AbstractMap.SimpleEntry<>("outputDriver2", "result2"))
                            .collect(Collectors.toMap(AbstractMap.SimpleEntry::getKey,
                                    AbstractMap.SimpleEntry::getValue)), null, null)));
}
 
Example 21
Project: collectors-utils   File: MaxEntryValueByCountingTest.java   Source Code and License 6 votes vote down vote up
@Test
public void should_return_a_correct_map_for_max_entry_value_by_counting_on_correct_stream() {

    // Given
    Map<Integer, Stream<String>> map = new HashMap<>();
    map.put(1, Stream.of("one", "two", "three"));
    map.put(2, Stream.of("one", "two", "two", "three"));
    map.put(3, Stream.of("one", "two", "two", "three", "three", "three"));
    Stream<Map.Entry<Integer, Stream<String>>> entries =
            FunctionsUtils.<Integer, Stream<String>>toStreamOfEntries().apply(map);

    Collector<Map.Entry<Integer, Stream<String>>, ?, Map<Integer, Map.Entry<String, Long>>> collector =
            CollectorsUtils.maxEntryValueByCounting();

    // When
    Map<Integer, Map.Entry<String, Long>> collect = entries.collect(collector);

    // Then
    assertThat(collect.size()).isEqualTo(3);
    assertThat(collect.get(1)).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("one", 1L));
    assertThat(collect.get(2)).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("two", 2L));
    assertThat(collect.get(3)).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("three", 3L));
}
 
Example 22
Project: collectors-utils   File: GroupingByAndMaxByTest.java   Source Code and License 6 votes vote down vote up
@Test
public void should_return_the_result_for_groupingBySelf_and_max_by_value_on_a_non_empty_stream() {

    // Given
    Stream<String> strings = Stream.of("one", "one", "two", "two", "two");

    Collector<String, ?, Optional<Map.Entry<String, Long>>> collector =
            CollectorsUtils.groupingBySelfAndMaxByValue(
                    counting()
            );

    // When
    Optional<Map.Entry<String, Long>> result = strings.collect(collector);

    // Then
    assertThat(result.isPresent()).isTrue();
    assertThat(result.get()).isEqualTo(new AbstractMap.SimpleImmutableEntry<>("two", 3L));
}
 
Example 23
Project: HCFCore   File: KitsCommand.java   Source Code and License 6 votes vote down vote up
public void onEnable() {
	if(config.get("kits") != null) {
		cooldowns = (HashMap<UUID, Map<String, Long>>) config.get("kits");
	}
	Bukkit.getScheduler().scheduleSyncRepeatingTask(hcf, new Runnable() {
		public void run() {
			if(cooldowns.size() > 0) {
				for(UUID uuid : cooldowns.keySet()) {
		            for(String strings : cooldowns.get(uuid).keySet()) {
		            	if(cooldowns.get(uuid).get(strings) <= 0L) {
		            		cooldowns.get(uuid).remove(strings);
		            	} else {
		            		cooldowns.put(uuid, (Map<String, Long>) new AbstractMap.SimpleEntry<String, Long>(strings, cooldowns.get(uuid).get(strings) - 1000L));
		            	}
		            }
	            }
			}
		}
	}, 20L, 20L);
}
 
Example 24
Project: openjdk-jdk10   File: ConcurrentSkipListMap.java   Source Code and License 6 votes vote down vote up
/**
 * Removes first entry; returns its snapshot.
 * @return null if empty, else snapshot of first entry
 */
private Map.Entry<K,V> doRemoveFirstEntry() {
    for (Node<K,V> b, n;;) {
        if ((n = (b = head.node).next) == null)
            return null;
        Node<K,V> f = n.next;
        if (n != b.next)
            continue;
        Object v = n.value;
        if (v == null) {
            n.helpDelete(b, f);
            continue;
        }
        if (!n.casValue(v, null))
            continue;
        if (!n.appendMarker(f) || !b.casNext(n, f))
            findFirst(); // retry
        clearIndexToFirst();
        @SuppressWarnings("unchecked") V vv = (V)v;
        return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, vv);
    }
}
 
Example 25
Project: joal   File: TorrentPersistentRefreshPeerIdGeneratorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void shouldConsiderEntryEvictableIfOlderThanTwoHours() {
    final PeerIdAlgorithm algo = Mockito.mock(PeerIdAlgorithm.class);
    final TorrentPersistentRefreshPeerIdGenerator generator = new TorrentPersistentRefreshPeerIdGenerator(algo, false);

    final AccessAwarePeerId oldKey = Mockito.mock(AccessAwarePeerId.class);
    Mockito.when(oldKey.getLastAccess()).thenReturn(LocalDateTime.now().minus(120, ChronoUnit.MINUTES));
    Mockito.when(oldKey.getPeerId()).thenReturn("-BT-C-");
    assertThat(generator.shouldEvictEntry(new AbstractMap.SimpleEntry<>(Mockito.mock(MockedTorrent.class), oldKey))).isTrue();
}
 
Example 26
Project: Lagerta   File: SubscriberConsumer.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override public Map.Entry<List<IgniteBiTuple<String, ?>>, List<Object>> apply(Long txId) {
    TransactionWrapper currentTx = buffer.get(txId);
    List<IgniteBiTuple<String, ?>> keys = currentTx.metadata().getCompositeKeys();
    List<Object> values = (List<Object>)serializer.deserialize(currentTx.data());
    return new AbstractMap.SimpleImmutableEntry<>(keys, values);
}
 
Example 27
Project: OpenJSharp   File: ConcurrentSkipListMap.java   Source Code and License 5 votes vote down vote up
Map.Entry<K,V> removeLowest() {
    Comparator<? super K> cmp = m.comparator;
    for (;;) {
        Node<K,V> n = loNode(cmp);
        if (n == null)
            return null;
        K k = n.key;
        if (!inBounds(k, cmp))
            return null;
        V v = m.doRemove(k, null);
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}
 
Example 28
Project: openjdk-jdk10   File: ResponderIdTests.java   Source Code and License 5 votes vote down vote up
@Override
public Map.Entry<Boolean, String> runTest() {
    Boolean pass = Boolean.FALSE;
    String message = null;
    try {
        respByName = new ResponderId(cert.getSubjectX500Principal());
        pass = Boolean.TRUE;
    } catch (Exception e) {
        e.printStackTrace(System.out);
        message = e.getClass().getName();
    }

    return new AbstractMap.SimpleEntry<>(pass, message);
}
 
Example 29
Project: fpc   File: Notifier.java   Source Code and License 5 votes vote down vote up
/**
 * Issues a Configuration Result over the Northbound over the NotificationPublishService
 * @param clientId - Client Identifier
 * @param opid - Operation Identifier
 * @param status - Operation Status
 * @param rt - Result Type
 * @param issueInternal - indicates if an internal framework notification should also occur
 * @param causeValue - cause value returned from DPN
 */
static public void issueConfigResult(
        ClientIdentifier clientId,
        OpIdentifier opid,
        OpStatus status,
        ResultType rt,
        boolean issueInternal,
        Short causeValue) {
    Long notificationId = NotificationInfo.next();

    ConfigResultNotification result = new ConfigResultNotificationBuilder()
            .setNotificationId(new NotificationId(notificationId))
            .setTimestamp(BigInteger.valueOf(System.currentTimeMillis()))
            .setValue(new ConfigResultBuilder()
                    .setOpId(opid)
                    .setOpStatus(status)
                    .setResultType(rt)
                    .setCauseValue(Long.valueOf(causeValue))
                    .build())
            .build();
    try {
    	String streamString = fpcCodecUtils.notificationToJsonString(Notify.class,
		        (DataObject) result,
		        true);
        streamString = streamString.replace("\n","");
        streamString = "event:application/json;/notification\ndata:"+streamString+"\n";
        NotificationService.blockingQueue.put(new AbstractMap.SimpleEntry<String,String>(clientId.getInt64().toString(),streamString));
        if (issueInternal &&
                (notificationService != null)) {
            notificationService.putNotification(result);
        }
    } catch (InterruptedException e) {
        LOG.warn("Notification Service Interruption occurred while sending a Read Notification");
        ErrorLog.logError(e.getStackTrace());
    } catch (Exception ee) {
    	ErrorLog.logError("Notifier Exception:   "+ee.getClass().getName()+" : "+ee.getLocalizedMessage(),ee.getStackTrace());
    }
}
 
Example 30
Project: Abacus-Lightweight-Stream-API   File: EntryStream.java   Source Code and License 5 votes vote down vote up
public static <K, V> EntryStream<K, V> zip(final K[] keys, final V[] values) {
    final BiFunction<K, V, Map.Entry<K, V>> zipFunction = new BiFunction<K, V, Map.Entry<K, V>>() {
        @Override
        public Entry<K, V> apply(K k, V v) {
            return new AbstractMap.SimpleImmutableEntry<>(k, v);
        }
    };

    final Function<Map.Entry<K, V>, Map.Entry<K, V>> mapper = Fn.identity();

    return Stream.zip(keys, values, zipFunction).mapToEntry(mapper);
}
 
Example 31
Project: java-web-servlet-filter   File: HttpServletRequestExtractAdapter.java   Source Code and License 5 votes vote down vote up
@Override
public Map.Entry<K, V> next() {
    if (mapEntry == null || (!listIterator.hasNext() && mapIterator.hasNext())) {
        mapEntry = mapIterator.next();
        listIterator = mapEntry.getValue().iterator();
    }

    if (listIterator.hasNext()) {
        return new AbstractMap.SimpleImmutableEntry<>(mapEntry.getKey(), listIterator.next());
    } else {
        return new AbstractMap.SimpleImmutableEntry<>(mapEntry.getKey(), null);
    }
}
 
Example 32
Project: traccar-service   File: JsonGeocoder.java   Source Code and License 5 votes vote down vote up
@Override
public void getAddress(
        final AddressFormat format, final double latitude,
        final double longitude, final ReverseGeocoderCallback callback) {

    if (cache != null) {
        String cachedAddress = cache.get(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude));
        if (cachedAddress != null) {
            callback.onSuccess(cachedAddress);
            return;
        }
    }

    Context.getAsyncHttpClient().prepareGet(String.format(url, latitude, longitude))
            .execute(new AsyncCompletionHandler() {
        @Override
        public Object onCompleted(Response response) throws Exception {
            try (JsonReader reader = Json.createReader(response.getResponseBodyAsStream())) {
                Address address = parseAddress(reader.readObject());
                if (address != null) {
                    String formattedAddress = format.format(address);
                    if (cache != null) {
                        cache.put(new AbstractMap.SimpleImmutableEntry<>(latitude, longitude), formattedAddress);
                    }
                    callback.onSuccess(formattedAddress);
                } else {
                    callback.onFailure(new GeocoderException("Empty address"));
                }
            }
            return null;
        }

        @Override
        public void onThrowable(Throwable t) {
            callback.onFailure(t);
        }
    });
}
 
Example 33
Project: Abacus-Lightweight-Stream-API   File: EntryStream.java   Source Code and License 5 votes vote down vote up
public <KK, VV> EntryStream<KK, VV> map(final Function<? super K, KK> keyMapper, final Function<? super V, VV> valueMapper) {
    final Function<Map.Entry<K, V>, Map.Entry<KK, VV>> mapper = new Function<Map.Entry<K, V>, Map.Entry<KK, VV>>() {
        @Override
        public Entry<KK, VV> apply(Entry<K, V> t) {
            return new AbstractMap.SimpleImmutableEntry<>(keyMapper.apply(t.getKey()), valueMapper.apply(t.getValue()));
        }
    };

    return map(mapper);
}
 
Example 34
Project: Abacus-Lightweight-Stream-API   File: EntryStream.java   Source Code and License 5 votes vote down vote up
public <KK> EntryStream<KK, V> flatMapKey(final Function<? super K, Stream<KK>> keyMapper) {
    final Function<Map.Entry<K, V>, Stream<Map.Entry<KK, V>>> mapper2 = new Function<Map.Entry<K, V>, Stream<Map.Entry<KK, V>>>() {
        @Override
        public Stream<Entry<KK, V>> apply(final Map.Entry<K, V> e) {
            return keyMapper.apply(e.getKey()).map(new Function<KK, Map.Entry<KK, V>>() {
                @Override
                public Map.Entry<KK, V> apply(KK kk) {
                    return new AbstractMap.SimpleImmutableEntry<>(kk, e.getValue());
                }
            });
        }
    };

    return flatMap(mapper2);
}
 
Example 35
Project: QuantTester   File: Portfolio.java   Source Code and License 5 votes vote down vote up
@Deprecated
public float getBalance(float price) {
	AbstractMap.SimpleEntry<String, Float> latestMarket = new AbstractMap.SimpleEntry<String, Float>("common", price);
	@SuppressWarnings("unchecked")
	AbstractMap.SimpleEntry<String, Float>[] latestMarkets = new AbstractMap.SimpleEntry[1];
	latestMarkets[0] = latestMarket;
	return getBalance(latestMarkets);
}
 
Example 36
Project: Lagerta   File: AbstractIgniteCommitterUnitTest.java   Source Code and License 5 votes vote down vote up
private static Map.Entry<List<IgniteBiTuple<String, List<Object>>>, List<List<Object>>> tx(
    Map.Entry<String, Object>... pairs
) {
    List<Object> keys = new ArrayList<>(pairs.length);
    List<Object> values = new ArrayList<>(pairs.length);

    for (Map.Entry<String, ?> pair : pairs) {
        keys.add(pair.getKey());
        values.add(pair.getValue());
    }
    IgniteBiTuple<String, List<Object>> cacheToKeys = new IgniteBiTuple<>(CACHE_NAME, keys);

    return new AbstractMap.SimpleImmutableEntry<>(Collections.singletonList(cacheToKeys),
        Collections.singletonList(values));
}
 
Example 37
Project: OpenJSharp   File: EditDistance.java   Source Code and License 5 votes vote down vote up
/**
 * Computes the edit distance between two strings.
 *
 * <p>
 * The complexity is O(nm) where n=a.length() and m=b.length().
 */
public static int editDistance( String a, String b ) {
    // let's check cache
    AbstractMap.SimpleEntry<String,String> entry = new AbstractMap.SimpleEntry<String, String>(a, b); // using this class to avoid creation of my own which will handle PAIR of values
    Integer result = null;
    if (CACHE.containsKey(entry))
        result = CACHE.get(entry); // looks like we have it

    if (result == null) {
        result = new EditDistance(a, b).calc();
        CACHE.put(entry, result); // cache the result
    }
    return result;
}
 
Example 38
Project: dremio-oss   File: NamespaceServiceImpl.java   Source Code and License 5 votes vote down vote up
@Override
public Iterable<Map.Entry<NamespaceKey, NameSpaceContainer>> find(FindByCondition condition) {
  return Iterables.transform(namespace.find(condition), new Function<Map.Entry<byte[], NameSpaceContainer>, Map.Entry<NamespaceKey, NameSpaceContainer>>() {
    @Override
    public Map.Entry<NamespaceKey, NameSpaceContainer> apply(Map.Entry<byte[], NameSpaceContainer> input) {
      return new AbstractMap.SimpleEntry<>(new NamespaceKey(input.getValue().getFullPathList()), input.getValue());
    }
  });
}
 
Example 39
Project: openjdk-jdk10   File: ConcurrentSkipListMap.java   Source Code and License 5 votes vote down vote up
Map.Entry<K,V> removeLowest() {
    Comparator<? super K> cmp = m.comparator;
    for (;;) {
        Node<K,V> n = loNode(cmp);
        if (n == null)
            return null;
        K k = n.key;
        if (!inBounds(k, cmp))
            return null;
        V v = m.doRemove(k, null);
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}
 
Example 40
Project: dragoman   File: MapMaker.java   Source Code and License 5 votes vote down vote up
@SafeVarargs
@SuppressWarnings("unchecked")
public static Map<String, Object> makeMap(AbstractMap.SimpleEntry<String, Object>... entries) {
  return Stream.of(entries)
      .collect(
          Collectors.toMap(AbstractMap.SimpleEntry::getKey, AbstractMap.SimpleEntry::getValue));
}
 
Example 41
Project: java-web-servlet-filter   File: MultivaluedMapFlatIteratorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testEmptyValue() {
    Map<String, List<String>> map = new HashMap<>();
    map.put("key", Collections.<String>emptyList());

    HttpServletRequestExtractAdapter.MultivaluedMapFlatIterator<String, String> iterator = new
            HttpServletRequestExtractAdapter.MultivaluedMapFlatIterator<>(map.entrySet());

    Assert.assertTrue(iterator.hasNext());
    Assert.assertEquals(new AbstractMap.SimpleImmutableEntry<>("key", null), iterator.next());
    Assert.assertFalse(iterator.hasNext());
}
 
Example 42
Project: JRediClients   File: RedissonBaseMapIterator.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
protected M getValue(final Entry<ScanObjectEntry, ScanObjectEntry> entry) {
    return (M)new AbstractMap.SimpleEntry<K, V>((K)entry.getKey().getObj(), (V)entry.getValue().getObj()) {

        @Override
        public V setValue(V value) {
            return put(entry, value);
        }

    };
}
 
Example 43
Project: JRediClients   File: RedissonMapReactiveIterator.java   Source Code and License 5 votes vote down vote up
M getValue(final Entry<ScanObjectEntry, ScanObjectEntry> entry) {
    return (M)new AbstractMap.SimpleEntry<K, V>((K)entry.getKey().getObj(), (V)entry.getValue().getObj()) {

        @Override
        public V setValue(V value) {
            Publisher<V> publisher = map.put((K) entry.getKey().getObj(), value);
            return ((Stream<V>)publisher).next().poll();
        }

    };
}
 
Example 44
Project: JRediClients   File: RedissonMultiMapIterator.java   Source Code and License 5 votes vote down vote up
@SuppressWarnings("unchecked")
M getValue(V entry) {
    return (M)new AbstractMap.SimpleEntry<K, V>(currentKey, entry) {

        @Override
        public V setValue(V value) {
            throw new UnsupportedOperationException();
        }

    };
}
 
Example 45
Project: JRediClients   File: RedissonMapTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testStringCodec() {
    Config config = createConfig();
    config.setCodec(StringCodec.INSTANCE);
    RedissonClient redisson = Redisson.create(config);

    RMap<String, String> rmap = redisson.getMap("TestRMap01");
    rmap.put("A", "1");
    rmap.put("B", "2");

    Iterator<Map.Entry<String, String>> iterator = rmap.entrySet().iterator();
    while (iterator.hasNext()) {
        Map.Entry<String, String> next = iterator.next();
        assertThat(next).isIn(new AbstractMap.SimpleEntry("A", "1"), new AbstractMap.SimpleEntry("B", "2"));
    }

    redisson.shutdown();
}
 
Example 46
Project: hadoop   File: FSDirRenameOp.java   Source Code and License 5 votes vote down vote up
/**
 * The new rename which has the POSIX semantic.
 */
static Map.Entry<BlocksMapUpdateInfo, HdfsFileStatus> renameToInt(
    FSDirectory fsd, final String srcArg, final String dstArg,
    boolean logRetryCache, Options.Rename... options)
    throws IOException {
  String src = srcArg;
  String dst = dstArg;
  if (NameNode.stateChangeLog.isDebugEnabled()) {
    NameNode.stateChangeLog.debug("DIR* NameSystem.renameTo: with options -" +
        " " + src + " to " + dst);
  }
  if (!DFSUtil.isValidName(dst)) {
    throw new InvalidPathException("Invalid name: " + dst);
  }
  final FSPermissionChecker pc = fsd.getPermissionChecker();

  byte[][] srcComponents = FSDirectory.getPathComponentsForReservedPath(src);
  byte[][] dstComponents = FSDirectory.getPathComponentsForReservedPath(dst);
  BlocksMapUpdateInfo collectedBlocks = new BlocksMapUpdateInfo();
  src = fsd.resolvePath(pc, src, srcComponents);
  dst = fsd.resolvePath(pc, dst, dstComponents);
  renameTo(fsd, pc, src, dst, collectedBlocks, logRetryCache, options);
  INodesInPath dstIIP = fsd.getINodesInPath(dst, false);
  HdfsFileStatus resultingStat = fsd.getAuditFileInfo(dstIIP);

  return new AbstractMap.SimpleImmutableEntry<>(
      collectedBlocks, resultingStat);
}
 
Example 47
Project: openjdk-jdk10   File: EntryTest.java   Source Code and License 5 votes vote down vote up
/**
 * getValue returns last setValue for SimpleEntry
 */
public void testSetValue1() {
    Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
    Map.Entry e = new AbstractMap.SimpleEntry(e2);
    assertEquals(k1, e.getKey());
    assertEquals(v1, e.getValue());
    e.setValue(k2);
    assertEquals(k2, e.getValue());
    assertFalse(e2.equals(e));
}
 
Example 48
Project: OpenJSharp   File: ConcurrentSkipListMap.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a key-value mapping associated with the greatest
 * key in this map, or {@code null} if the map is empty.
 * The returned entry does <em>not</em> support
 * the {@code Entry.setValue} method.
 */
public Map.Entry<K,V> lastEntry() {
    for (;;) {
        Node<K,V> n = findLast();
        if (n == null)
            return null;
        AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
        if (e != null)
            return e;
    }
}
 
Example 49
Project: fpc   File: EventClient.java   Source Code and License 5 votes vote down vote up
@Override
        protected void onCharReceived(final CharBuffer buf, final IOControl ioctrl) throws IOException {
        	try {
        		char[] charArray = new char[buf.remaining()];
        		System.arraycopy(buf.array(), 0, charArray, 0, buf.remaining());
        		CharBuffer charBuffer =  CharBuffer.wrap(charArray);
	ParseStream.blockingQueue.put(new AbstractMap.SimpleEntry<String, CharBuffer>(clientUri, charBuffer));
} catch (InterruptedException e) {
	// TODO Auto-generated catch block
	e.printStackTrace();
}
        }
 
Example 50
Project: emr-nlp-server   File: LibSVMFileFormat.java   Source Code and License 5 votes vote down vote up
/**
 * Convert a feature vector string into list of index:value.
 * 
 * @param featureVectorStr
 * @return
 * @throws Exception 
 */
protected List<Map.Entry<String,Double>> extractFeatureVector(
        String featureVectorStr) throws Exception {
    List<Map.Entry<String,Double>> featureVector = new ArrayList<>();
    String[] itemStrList = featureVectorStr.split(svmLightDelimiter);
    String[] itemStr;
    Map.Entry<String, Double> item;
    for(int i = 1; i < itemStrList.length; i++) {
        itemStr = itemStrList[i].split(svmLightFeatureValueDelimiter);
        item = new AbstractMap.SimpleEntry<String, Double>(itemStr[0], Double.parseDouble(itemStr[1]));
        featureVector.add(item);
    }
    
    return featureVector;
}
 
Example 51
Project: alfresco-repository   File: DefaultSimpleCache.java   Source Code and License 5 votes vote down vote up
@Override
public V get(K key)
{
    AbstractMap.SimpleImmutableEntry<K, V> kvp = cache.getIfPresent(key);
    if (kvp == null)
    {
        return null;
    }
    return kvp.getValue();
}
 
Example 52
Project: ibm-cos-sdk-java   File: AbstractProfilesConfigFileScanner.java   Source Code and License 5 votes vote down vote up
private static Entry<String, String> parsePropertyLine(String propertyLine) {
    String[] pair = propertyLine.split("=", 2);
    if (pair.length != 2) {
        throw new IllegalArgumentException(
                "Invalid property format: no '=' character is found in the line ["
                + propertyLine + "].");
    }

    String propertyKey   = pair[0].trim();
    String propertyValue = pair[1].trim();

    return new AbstractMap.SimpleImmutableEntry<String, String>(propertyKey, propertyValue);
}
 
Example 53
Project: dremio-oss   File: MapWithOrdinal.java   Source Code and License 5 votes vote down vote up
@Override
public V remove(Object key) {
  final Entry<Integer, V> oldPair = primary.remove(key);
  if (oldPair!=null) {
    final int lastOrdinal = secondary.size();
    final V last = secondary.get(lastOrdinal);
    // normalize mappings so that all numbers until primary.size() is assigned
    // swap the last element with the deleted one
    secondary.put(oldPair.getKey(), last);
    primary.put((K) key, new AbstractMap.SimpleImmutableEntry<>(oldPair.getKey(), last));
  }
  return oldPair==null ? null:oldPair.getValue();
}
 
Example 54
Project: hanlpStudy   File: StringDictionary.java   Source Code and License 5 votes vote down vote up
@Override
protected Map.Entry<String, String> onGenerateEntry(String line)
{
    String[] paramArray = line.split(separator, 2);
    if (paramArray.length != 2)
    {
        logger.warning("词典有一行读取错误: " + line);
        return null;
    }
    return new AbstractMap.SimpleEntry<String, String>(paramArray[0], paramArray[1]);
}
 
Example 55
Project: OpenJSharp   File: ConcurrentSkipListMap.java   Source Code and License 5 votes vote down vote up
/**
 * Returns a key-value mapping associated with the least
 * key in this map, or {@code null} if the map is empty.
 * The returned entry does <em>not</em> support
 * the {@code Entry.setValue} method.
 */
public Map.Entry<K,V> firstEntry() {
    for (;;) {
        Node<K,V> n = findFirst();
        if (n == null)
            return null;
        AbstractMap.SimpleImmutableEntry<K,V> e = n.createSnapshot();
        if (e != null)
            return e;
    }
}
 
Example 56
Project: eventapis   File: OperationContext.java   Source Code and License 5 votes vote down vote up
public void switchContext(String opId) {
    operationContext.set(new AbstractMap.SimpleEntry<>(opId, null));
    MDC.put("opId", opId);
}
 
Example 57
Project: chromium-net-for-android   File: CronetUrlRequestTest.java   Source Code and License 5 votes vote down vote up
@SmallTest
@Feature({"Cronet"})
public void testResponseHeadersList() throws Exception {
    TestUrlRequestCallback callback = startAndWaitForComplete(NativeTestServer.getSuccessURL());
    assertEquals(200, callback.mResponseInfo.getHttpStatusCode());
    List<Map.Entry<String, String>> responseHeaders =
            callback.mResponseInfo.getAllHeadersAsList();

    MoreAsserts.assertContentsInOrder(responseHeaders,
            new AbstractMap.SimpleEntry<>("Content-Type", "text/plain"),
            new AbstractMap.SimpleEntry<>("Access-Control-Allow-Origin", "*"),
            new AbstractMap.SimpleEntry<>("header-name", "header-value"),
            new AbstractMap.SimpleEntry<>("multi-header-name", "header-value1"),
            new AbstractMap.SimpleEntry<>("multi-header-name", "header-value2"));
}
 
Example 58
Project: java-web-servlet-filter   File: MultivaluedMapFlatIteratorTest.java   Source Code and License 5 votes vote down vote up
@Test
public void testOneKeyOneValue() {
    Map<String, List<String>> map = new HashMap<>();
    map.put("key", new ArrayList<>(Arrays.asList("value")));

    HttpServletRequestExtractAdapter.MultivaluedMapFlatIterator<String, String> iterator = new
            HttpServletRequestExtractAdapter.MultivaluedMapFlatIterator<>(map.entrySet());

    Assert.assertTrue(iterator.hasNext());
    Assert.assertEquals(new AbstractMap.SimpleImmutableEntry<>("key", "value"), iterator.next());
    Assert.assertFalse(iterator.hasNext());
}
 
Example 59
Project: dhus-core   File: SortedMap.java   Source Code and License 5 votes vote down vote up
@Override
public Set<Entry<K, V>> entrySet()
{
   return new AbstractSet()
   {
      @Override
      public Iterator iterator()
      {
         final Iterator<K> it = iterableKeys.iterator();
         return new Iterator()
         {

            @Override
            public boolean hasNext()
            {
               return it.hasNext();
            }

            @Override
            public Object next()
            {
               K key = it.next();
               return new AbstractMap.SimpleImmutableEntry<>(key, index.get(key));
            }

            @Override
            public void remove()
            {
               throw new UnsupportedOperationException("Read only.");
            }
         };
      }

      @Override
      public int size()
      {
         return index.size();
      }
   };
}
 
Example 60
Project: jdk8u-jdk   File: ConcurrentSkipListMap.java   Source Code and License 5 votes vote down vote up
Map.Entry<K,V> removeHighest() {
    Comparator<? super K> cmp = m.comparator;
    for (;;) {
        Node<K,V> n = hiNode(cmp);
        if (n == null)
            return null;
        K k = n.key;
        if (!inBounds(k, cmp))
            return null;
        V v = m.doRemove(k, null);
        if (v != null)
            return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
    }
}