static { ID_TO_SUPPLIER = unmodifiableMap( Arrays.stream(ElasticsearchExceptionHandle.values()) .collect(Collectors.toMap(e -> e.id, e -> e.constructor))); CLASS_TO_ELASTICSEARCH_EXCEPTION_HANDLE = unmodifiableMap( Arrays.stream(ElasticsearchExceptionHandle.values()) .collect(Collectors.toMap(e -> e.exceptionClass, e -> e))); }
/** * reads all methods by the action-annotations for building agent-actions * * @param p_class class * @param p_root root class * @return stream of all methods with inheritance */ private static Stream<Method> methods(final Class<?> p_class, final Class<?> p_root) { final Pair<Boolean, IAgentAction.EAccess> l_classannotation = CCommon.isActionClass(p_class); if (!l_classannotation.getLeft()) return p_class.getSuperclass() == null ? Stream.of() : methods(p_class.getSuperclass(), p_root); final Predicate<Method> l_filter = IAgentAction.EAccess.WHITELIST.equals(l_classannotation.getRight()) ? i -> !CCommon.isActionFiltered(i, p_root) : i -> CCommon.isActionFiltered(i, p_root); return Stream.concat( Arrays.stream(p_class.getDeclaredMethods()) .parallel() .map( i -> { i.setAccessible(true); return i; }) .filter(i -> !Modifier.isAbstract(i.getModifiers())) .filter(i -> !Modifier.isInterface(i.getModifiers())) .filter(i -> !Modifier.isNative(i.getModifiers())) .filter(i -> !Modifier.isStatic(i.getModifiers())) .filter(l_filter), methods(p_class.getSuperclass(), p_root)); }
@Override public Optional<Suggestion> requestPlayerSuggestion(Player player, Room room) { char userWantsToMakeSuggestion = '\0'; while (userWantsToMakeSuggestion != 'Y' && userWantsToMakeSuggestion != 'N') { this.out.println("Do you want to make an suggestion (Y/N)?"); this.out.println("Your cards are: " + player.cards); userWantsToMakeSuggestion = this.scanner.next().charAt(0); } if (userWantsToMakeSuggestion == 'Y') { this.out.printf("You suggest it was done in the %s, by: \n", room); Stream<String> suspects = Arrays.stream(CluedoCharacter.values()).map(CluedoCharacter::toString); CluedoCharacter suspect = CluedoCharacter.values()[this.selectOptionFromList(suspects)]; this.out.println("with the "); Stream<String> weapons = Arrays.stream(Weapon.values()).map(Weapon::toString); Weapon weapon = Weapon.values()[this.selectOptionFromList(weapons)]; return Optional.of(new Suggestion(suspect, weapon, room)); } else { return Optional.empty(); } }
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] numbers = sc.nextLine().split(" "); String sort = sc.nextLine(); if (sort.equals("Ascending")) { List<Integer> output = Arrays.stream(numbers).map(Integer::parseInt).sorted().collect(Collectors.toList()); for (Object items : output) { System.out.print(items + " "); } } else if (sort.equals("Descending")) { List<Integer> output = Arrays.stream(numbers) .map(Integer::parseInt) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); for (Object items : output) { System.out.print(items + " "); } } }
public static void main(String[] args) { AccessIdentifiers2 ac = new AccessIdentifiers2(); System.out.println(ac.getClass().getName()); System.out.println( Arrays.stream(ac.getClass().getDeclaredFields()) .map(Field::getName) .collect(Collectors.joining(" || "))); ; System.out.println( Arrays.stream(ac.getClass().getDeclaredMethods()) .map(Method::getName) .collect(Collectors.joining(" || "))); System.out.println( Arrays.stream(ac.getClass().getDeclaredMethods()) .map(Method::getReturnType) .map(Class::getName) .collect(Collectors.joining(" || "))); System.out.println( Arrays.stream(ac.getClass().getInterfaces()) .map(Class::getName) .collect(Collectors.joining(" || "))); System.out.println(ac.getClass().getDeclaredFields().length); System.out.println(ac.getClass().getDeclaredMethods().length); }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); Integer[] startTimeInfo = Arrays.stream(scanner.nextLine().split(":+")) .map(Integer::parseInt) .toArray(Integer[]::new); Integer[] endTimeInfo = Arrays.stream(scanner.nextLine().split(":+")) .map(Integer::parseInt) .toArray(Integer[]::new); Integer minutesDifferenceFromSeconds = 0; Integer seconds = startTimeInfo[2] - endTimeInfo[2]; if (seconds < 0) { seconds = 60 + seconds; minutesDifferenceFromSeconds--; } Integer hoursDifferenceFromMinutes = 0; Integer minutes = (startTimeInfo[1] - endTimeInfo[1]) + minutesDifferenceFromSeconds; if (minutes < 0) { minutes = 60 + minutes; hoursDifferenceFromMinutes--; } Integer hours = (startTimeInfo[0] - endTimeInfo[0]) + hoursDifferenceFromMinutes; System.out.printf("%d:%02d:%02d%n", hours, minutes, seconds); }
public static void main(String[] args) { String[] strings = {"Red", "orange", "Yellow", "green", "Blue", "indigo", "Violet"}; // display original strings System.out.printf("Original strings: %s%n", Arrays.asList(strings)); // strings in uppercase System.out.printf( "strings in uppercase: %s%n", Arrays.stream(strings).map(String::toUpperCase).collect(Collectors.toList())); // strings less than "m" (case insensitive) sorted ascending System.out.printf( "strings greater than m sorted ascending: %s%n", Arrays.stream(strings) .filter(s -> s.compareToIgnoreCase("m") < 0) .sorted(String.CASE_INSENSITIVE_ORDER) .collect(Collectors.toList())); // strings less than "m" (case insensitive) sorted descending System.out.printf( "strings greater than m sorted descending: %s%n", Arrays.stream(strings) .filter(s -> s.compareToIgnoreCase("m") < 0) .sorted(String.CASE_INSENSITIVE_ORDER.reversed()) .collect(Collectors.toList())); }
@Override public DefaultDataBuffer write(ByteBuffer... byteBuffers) { Assert.notEmpty(byteBuffers, "'byteBuffers' must not be empty"); int extraCapacity = Arrays.stream(byteBuffers).mapToInt(ByteBuffer::remaining).sum(); ensureExtraCapacity(extraCapacity); Arrays.stream(byteBuffers) .forEach(byteBuffer -> writeInternal(buffer -> buffer.put(byteBuffer))); return this; }
@Test @Ignore public void testKeyExtraction() { Employee[] emps = new Employee[] {new Employee(), new Employee(), new Employee()}; System.out.println("Unsorted"); Arrays.stream(emps).forEach(System.out::println); System.out.println("Sorted with key extractor"); Arrays.sort(emps, Comparator.comparing(Employee::getId)); Arrays.stream(emps).forEach(System.out::println); }
public static void main(String[] args) { Scanner scanner = new Scanner(System.in); String inputData = scanner.nextLine(); List<Team> championsLeague = new ArrayList<>(); while (!inputData.equals("stop")) { String[] inputArgs = inputData.split("\\|+"); String firstTeamName = inputArgs[0].trim(); String secondTeamName = inputArgs[1].trim(); if (!championsLeague.stream().anyMatch(t -> t.name.equals(firstTeamName))) { championsLeague.add(new Team(firstTeamName)); } if (!championsLeague.stream().anyMatch(t -> t.name.equals(secondTeamName))) { championsLeague.add(new Team(secondTeamName)); } Integer[] firstMatchResult = Arrays.stream(inputArgs[2].trim().split(":+")) .map(Integer::parseInt) .toArray(Integer[]::new); Integer[] secondMatchResult = Arrays.stream(inputArgs[3].trim().split(":+")) .map(Integer::parseInt) .toArray(Integer[]::new); Integer firstTeamGoals = firstMatchResult[0] + secondMatchResult[1]; Integer secondTeamGoals = firstMatchResult[1] + secondMatchResult[0]; Team firstTeam = championsLeague.stream().filter(t -> t.name.equals(firstTeamName)).findFirst().get(); Team secondTeam = championsLeague.stream().filter(t -> t.name.equals(secondTeamName)).findFirst().get(); if (firstTeamGoals > secondTeamGoals) { firstTeam.wins++; } else if (secondTeamGoals > firstTeamGoals) { secondTeam.wins++; } else if (firstTeamGoals.equals(secondTeamGoals)) { int firstTeamAwayGoals = secondMatchResult[1]; int secondTeamAwayGoals = firstMatchResult[1]; if (firstTeamAwayGoals > secondTeamAwayGoals) { firstTeam.wins++; } else { secondTeam.wins++; } } firstTeam.opponents.add(secondTeam); secondTeam.opponents.add(firstTeam); inputData = scanner.nextLine(); } Collections.sort(championsLeague); championsLeague.forEach(System.out::println); }
public static float doVarianceViaStream(int[] sample) { Double average = Arrays.stream(sample).parallel().average().getAsDouble(); Double variance = Arrays.stream(sample) .parallel() .mapToDouble(p -> ((new Double(p) - average) * (new Double(p) - average))) .sum() / sample.length; return variance.floatValue(); }
@Test public void testRemoveUnfinishedLeftovers_abort_multipleFolders() throws Throwable { ColumnFamilyStore cfs = MockSchema.newCFS(KEYSPACE); File origiFolder = new Directories(cfs.metadata).getDirectoryForNewSSTables(); File dataFolder1 = new File(origiFolder, "1"); File dataFolder2 = new File(origiFolder, "2"); Files.createDirectories(dataFolder1.toPath()); Files.createDirectories(dataFolder2.toPath()); SSTableReader[] sstables = { sstable(dataFolder1, cfs, 0, 128), sstable(dataFolder1, cfs, 1, 128), sstable(dataFolder2, cfs, 2, 128), sstable(dataFolder2, cfs, 3, 128) }; LogTransaction log = new LogTransaction(OperationType.COMPACTION); assertNotNull(log); LogTransaction.SSTableTidier[] tidiers = { log.obsoleted(sstables[0]), log.obsoleted(sstables[2]) }; log.trackNew(sstables[1]); log.trackNew(sstables[3]); Collection<File> logFiles = log.logFiles(); Assert.assertEquals(2, logFiles.size()); // fake an abort log.txnFile().abort(); Arrays.stream(sstables).forEach(s -> s.selfRef().release()); // test listing Assert.assertEquals( sstables[1].getAllFilePaths().stream().map(File::new).collect(Collectors.toSet()), getTemporaryFiles(dataFolder1)); Assert.assertEquals( sstables[3].getAllFilePaths().stream().map(File::new).collect(Collectors.toSet()), getTemporaryFiles(dataFolder2)); // normally called at startup LogTransaction.removeUnfinishedLeftovers(Arrays.asList(dataFolder1, dataFolder2)); // old tables should be only table left assertFiles(dataFolder1.getPath(), new HashSet<>(sstables[0].getAllFilePaths())); assertFiles(dataFolder2.getPath(), new HashSet<>(sstables[2].getAllFilePaths())); // complete the transaction to avoid LEAK errors Arrays.stream(tidiers).forEach(LogTransaction.SSTableTidier::run); assertNull(log.complete(null)); }
/** * A[N] N is integer in range [2..100,000] each element of A is an integer within range * [0..1,000,000] * * @param A non null, non-empty array */ public int solution(int[] A) { // write your code in Java SE 8 // if there are duplicates, the minimum will be 0 IntStream numbers = Arrays.stream(A); if (numbers.distinct().count() < A.length) { return 0; } else { int firstMin = Arrays.stream(A).min().getAsInt(); int secondMin = Arrays.stream(A).filter(n -> n != firstMin).min().getAsInt(); return secondMin - firstMin; } }
public static double variance(String town, String strng) { if (town == null || strng == null) { return 0d; } double[] townTemp = getTownTemp(town, strng); if (townTemp.length == 0) { return -1d; } double average = Arrays.stream(townTemp).average().getAsDouble(); double variance = Arrays.stream(townTemp).map(p -> (p - average) * (p - average)).sum() / townTemp.length; return variance; }
public boolean contentLongText(String selector, String text) { String shrinkText = Arrays.stream(text.split("\n")).map(v -> v.trim()).collect(Collectors.joining()); Elements es = document().select(selector); for (Element e : es) { String fullText = Arrays.stream(e.html().trim().split("<(br|BR|Br|bR) */?>")) .map(v -> Arrays.stream(v.trim().split("\n")).collect(Collectors.joining())) .collect(Collectors.joining("")); if (fullText.equals(shrinkText)) return wrap(true); } addViolation(String.format("入力されたはずのテキストがDOM要素 '%s' に表示されていません", selector)); return wrap(false); }
private static boolean checkCompile(String[] files) throws Exception { String combined = Arrays.stream(files).collect(Collectors.joining(" ")); List<String> args = Arrays.stream(combined.split(" ")) .filter(f -> f.endsWith(".java")) .collect(Collectors.toList()); if (args.size() == 0) { return true; } args.add(0, "javac"); ProcessBuilder pcb = new ProcessBuilder(args); Process p = pcb.start(); p.waitFor(); return p.exitValue() == 0; }
public static void main(String[] args) { // int[] A = { 2, 5, 7, 4, 8, 1 }; int[] A = {14, 35, 27, 10, 35, 19, 42, 44}; int[] sortedArr = sort(A); Arrays.stream(sortedArr).forEach(System.out::print); A = new int[] {-2, -5, 7, 4, -8, 1}; sortedArr = sort(A); Arrays.stream(sortedArr).forEach(System.out::print); A = new int[] {2, 1, 4, 5, 7}; sortedArr = sort(A); Arrays.stream(sortedArr).forEach(System.out::print); }
public static <T> List<T> createFromList(String raw, TypedOption<T> option) { if (raw == null) { return Collections.emptyList(); } final String[] segments = raw.split(option.getListSeparator()); return Arrays.stream(segments).map(s -> create(s.trim(), option)).collect(Collectors.toList()); }
// helper method to test if required files are present in the runtime public void testRuntime(RelativeFileSet runtime, String[] file) throws ConfigException { if (runtime == null) { return; // null runtime is ok (request to use system) } Pattern[] weave = Arrays.stream(file).map(Pattern::compile).toArray(Pattern[]::new); if (!runtime .getIncludedFiles() .stream() .anyMatch(s -> Arrays.stream(weave).anyMatch(pattern -> pattern.matcher(s).matches()))) { throw new ConfigException( MessageFormat.format(I18N.getString("error.jre-missing-file"), Arrays.toString(file)), I18N.getString("error.jre-missing-file.advice")); } }
/** * Gets the tiles that need to be deleted due to the detonating of the flame gem. * * @param tile the flame gem * @return tiles, the list of tiles to be deleted. */ public List<Tile> getTilesToDeleteFlame(Tile tile) { final Point[] translations = { new Point(-1, 0), new Point(1, 1), new Point(0, 1), new Point(-1, 1), new Point(1, 0), new Point(-1, -1), new Point(0, -1), new Point(1, -1) }; tile.detonate = true; List<Tile> tiles = Arrays.stream(translations) .map(p -> new Point(tile.getX() + p.x, tile.getY() + p.y)) .filter(p -> board.validBorders(p.x, p.y)) .map(p -> board.getTileAt(p.x, p.y)) .filter(t -> !t.detonate) .collect(Collectors.toList()); checkForSpecialTile(tiles); if (!tiles.contains(tile)) { tiles.add(tile); } return tiles; }
@Override public void handle(ServiceRequest<GetEndpointsRequest, GetEndpointsResponse> service) throws UaException { GetEndpointsRequest request = service.getRequest(); String endpointUrl = request.getEndpointUrl(); if (endpointUrl == null) endpointUrl = ""; UaTcpStackServer server = servers.get(endpointUrl); EndpointDescription[] endpoints = (server != null) ? server.getEndpointDescriptions() : new EndpointDescription[0]; List<String> profileUris = request.getProfileUris() != null ? Lists.newArrayList(request.getProfileUris()) : Lists.newArrayList(); EndpointDescription[] filtered = Arrays.stream(endpoints) .filter(ed -> filterProfileUris(ed, profileUris)) .filter(this::filterEndpointUrls) .toArray(EndpointDescription[]::new); service.setResponse(new GetEndpointsResponse(service.createResponseHeader(), filtered)); }
@Override public Set<ArtifactSpec> resolveAll(final Set<ArtifactSpec> specs) { resetListeners(); final MavenResolvedArtifact[] artifacts; try { artifacts = this.resolver .resolve(specs.stream().map(ArtifactSpec::mavenGav).collect(Collectors.toList())) .withTransitivity() .as(MavenResolvedArtifact.class); } finally { completeTransferListener(); } return Arrays.stream(artifacts) .map( artifact -> { final MavenCoordinate coord = artifact.getCoordinate(); return new ArtifactSpec( "compile", coord.getGroupId(), coord.getArtifactId(), coord.getVersion(), coord.getPackaging().getId(), coord.getClassifier(), artifact.asFile()); }) .collect(Collectors.toSet()); }
public BoxPlot(Frame df, GOpt... opts) { this.vars = df.varStream().filter(var -> var.stream().complete().count() > 0).toArray(Var[]::new); this.names = Arrays.stream(vars).map(Var::name).toArray(String[]::new); this.options.apply(opts); initialize(); }
public String parseUri(String uri, String... uris) throws Exception { return parseUri( uri, uris != null ? Arrays.stream(uris).map(PropertiesLocation::new).collect(Collectors.toList()) : Collections.emptyList()); }
@Override protected Endpoint createEndpoint(String uri, String remaining, Map<String, Object> parameters) throws Exception { List<PropertiesLocation> paths = locations; Boolean ignoreMissingLocationLoc = getAndRemoveParameter(parameters, "ignoreMissingLocation", Boolean.class); if (ignoreMissingLocationLoc != null) { ignoreMissingLocation = ignoreMissingLocationLoc; } // override default locations String locations = getAndRemoveParameter(parameters, "locations", String.class); if (locations != null) { LOG.trace("Overriding default locations with location: {}", locations); paths = Arrays.stream(locations.split(",")) .map(PropertiesLocation::new) .collect(Collectors.toList()); } String endpointUri = parseUri(remaining, paths); LOG.debug("Endpoint uri parsed as: {}", endpointUri); Endpoint delegate = getCamelContext().getEndpoint(endpointUri); PropertiesEndpoint answer = new PropertiesEndpoint(uri, delegate, this); setProperties(answer, parameters); return answer; }
/** * class filter of an action to use it * * @param p_method method for checking * @param p_root root class * @return boolean flag of check result */ private static boolean isActionFiltered(final Method p_method, final Class<?> p_root) { return p_method.isAnnotationPresent(IAgentActionFilter.class) && ((p_method.getAnnotation(IAgentActionFilter.class).classes().length == 0) || (Arrays.stream(p_method.getAnnotation(IAgentActionFilter.class).classes()) .parallel() .anyMatch(p_root::equals))); }
private void runExperiment(String experimentCode) { Class experimentClass = Arrays.stream(experimentsAvailable) .filter( (Class<? extends BaseExperiment> filteredexperimentClass) -> { try { return filteredexperimentClass .getConstructor() .newInstance() .getCodeName() .compareTo(experimentCode) == 0; } catch (Exception ex) { Logger.getLogger(Runner.class.getName()).log(Level.SEVERE, null, ex); } return false; }) .findFirst() .orElse(null); if (experimentClass != null) { try { BaseExperiment experiment = (BaseExperiment) experimentClass.getConstructor().newInstance(); experiment.run(arguments); } catch (Exception ex) { Logger.getLogger(Runner.class.getName()).log(Level.SEVERE, null, ex); } } }
/** * returns actions by a class * * @note class must be an inheritance of the IAgent interface * @param p_class class list * @return action stream */ @SuppressWarnings("unchecked") public static Stream<IAction> actionsFromAgentClass(final Class<?>... p_class) { return p_class == null || p_class.length == 0 ? Stream.of() : Arrays.stream(p_class) .parallel() .filter(IAgent.class::isAssignableFrom) .flatMap(i -> CCommon.methods(i, i)) .map( i -> { try { return (IAction) new CMethodAction(i); } catch (final IllegalAccessException l_exception) { LOGGER.warning( CCommon.languagestring(CCommon.class, "actioninstantiate", i, l_exception)); return null; } }) // action can be instantiate .filter(Objects::nonNull) // check usable action name .filter(CCommon::actionusable); }
public static String threadName(Settings settings, String... names) { String namePrefix = Arrays.stream(names) .filter(name -> name != null) .collect(Collectors.joining(".", "[", "]")); return threadName(settings, namePrefix); }
@NotNull private static PsiElement[] extractReferencedVariables(@NotNull PsiTypeElement typeElement) { final PsiElement parent = typeElement.getParent(); if (parent instanceof PsiVariable) { if (parent instanceof PsiField) { PsiField aField = (PsiField) parent; List<PsiField> fields = new ArrayList<>(); while (true) { fields.add(aField); aField = PsiTreeUtil.getNextSiblingOfType(aField, PsiField.class); if (aField == null || aField.getTypeElement() != typeElement) { return fields.toArray(new PsiElement[fields.size()]); } } } else if (parent instanceof PsiLocalVariable) { final PsiDeclarationStatement declaration = PsiTreeUtil.getParentOfType(parent, PsiDeclarationStatement.class); if (declaration != null) { return Arrays.stream(declaration.getDeclaredElements()) .filter(PsiVariable.class::isInstance) .toArray(PsiVariable[]::new); } } return new PsiElement[] {parent}; } else { return PsiElement.EMPTY_ARRAY; } }